I have this flow in my app:
declare endpoints:
public interface EndPoints {
@GET(Constants.POPULAR)
Call<AllData> getAllData(
@Query("api_key") String apiKey
);
}
Retrofit service:
private static EndPoints endPoints = retrofit.create(EndPoints.class);
public static EndPoints getEndpoints() {
return endPoints ;
}
And I call this inside my view model:
private void getDataFromApi() {
Call<AllData> call = RetrofitService.getEndPoints().getAllData(Constants.API_KEY);
call.enqueue(new Callback<AllData>() {
@Override
public void onResponse(Call<AllData> call, Response<AllData> response) {
}
if (response.isSuccessful()) {
_allData.setValue(response.body());
}
@Override
public void onFailure(Call<AllData> call, Throwable t) {
}
});
}
Base Activity:
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutId());
}
Progress bar layout(I updated this instead of using frame layout every xml file, I created xml called progress bar layout and I want to inflate this every call):
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
How can I set progress bar every api call?
Initally I checked in getDataFromApi if is loading or not, set the value into bool LiveData and observed this inside my activity.
The problem with this is it's an insane amount of code duplication.
Every api call I need to set loading state, every activity I need to observer the loading state and call View.Visible and View.Hide and every activity xml I need to create frame layout with progress bar.
I believe the answer is somewhere inside the base activity as it is the only place that can "control" all the activities in the app, but I can't think of a way of solving this problem