A better approach is to consolidate this piece of logic into a central location. For this you can use an interceptor and just broadcast a local intent on any request your app makes.
Take a look to this Interceptor class written in Kotlin (Same works on Java):
internal class BusyInterceptor constructor(val appContext: Context) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val t1 = System.nanoTime()
// Times are different, so it does handle request and response at the same time
Log.d("REQUEST BUSY INTERCEPTOR------------>","request time: " + t1)
val intent = Intent()
intent.action = "IS_BUSY"
intent.putExtra("isBusy", true)
LocalBroadcastManager.getInstance(appContext).sendBroadcast(intent)
val response: Response = chain.proceed(request)
val t2 = System.nanoTime()
Log.d("RESPONSE BUSY INTERCEPTOR------------>","request time: " + t2)
val intent2 = Intent()
intent2.action = "IS_BUSY"
intent2.putExtra("isBusy", false)
LocalBroadcastManager.getInstance(appContext).sendBroadcast(intent2)
return response
}
}
Then you just add the interceptor to your okhttp client:
// Add Busy Interceptor
val busyInterceptor = BusyInterceptor(appContext)
okHttpClient.addInterceptor(busyInterceptor)
This way, you are not dependent on any specific activity/fragment anymore, you just have to make sure you are using an Application file, and registering for the broadcast.
i.e. MyApplication.java:
@Override
public void onCreate() {
super.onCreate();
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getBooleanExtra("isBusy", false)){
ProgressHUD.showDummyProcessing(getCurrentActivity());
} else {
ProgressHUD.hideDummyProcessing(getCurrentActivity());
}
}
};
IntentFilter filter = new IntentFilter("IS_BUSY");
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, filter);
This gives you the flexibility to decide what you want to do every time a request is made regardless where the user is currently at.
For simplicity I didn't include a queue logic to manage multiple/parallel requests, but its fairly simple to keep track of this at the same file using ArrayList or similar.
Also, some this supports "silent" requests where you don't want to display any feedback to the user (analytics, logging, etc), just pass additional "extras" in the intent :)