'Cancel all Previous Api call in Android - Retrofit - Using module

I have created below module in my android application.

val appNetworkModule = module {
// Dependency: OkHttpClient
single {
    var okHttpClient=OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .addInterceptor(get<Interceptor>("LOGGING_INTERCEPTOR"))
        .addInterceptor(get<Interceptor>("OK_HTTP_INTERCEPTOR"))
        .build()
  }
}

Now, I have to clear all the previous api calls while doing Logout from the app. So, I need to access the variable used in here as above named : okHttpClient

I am trying to access it as below to cancel all the previous api calls in my main activity:

appNetworkModule.okHttpClient.dispatcher.cancelAll()

But, okHttpClient is not accessible.

What might be the issue?



Solution 1:[1]

I might be late here, but the correct answer is that since it is defined in the module (Provided that you are using koin as a DI library). We need to inject it in our required class (where we need to call the okHttpClient) either using a constructor injection or using a field injection. So our code will be something like this.

Using Construction Injection: Make sure your Class TestClass gets the injected okHttpClient for example define the TestClass in the module like this single { TestClass(get()) }

class TestClass(private val okHttpClient: OkHttpClient) {

 fun clearAllApis(){
   okHttpClient.dispatcher.cancelAll()
 }
}

Using field injection: If you need to use field injection instead

class TestClass {

private val okHttpClient : OkHttpClient by inject() //If it is extended from Android platform class like AppCompatActivity, Fragment etc. or a KoinComponent extended class
private val okHttpClient : OkHttpClient by inject(OkHttpClient::class.java) //Otherwise

 fun clearAllApis(){
  okHttpClient.dispatcher.cancelAll()
 }
}

Make sure .inject() is from org.koin.android.ext.android.inject

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ehtisham Ali Shah