Koin + Retrofit adding header at run time

Viewed 2585

I have a coin and retrofit based project in MVVM architecture. I want to print the data with 'viewmodel' and add the value of 'token' to the header at run time after I register this project. But I couldn't provide the context structure needed to get the token I saved in SharedPreferences. How can I handle this in its cleanest form?

 fun createNetworkClient(baseUrl: String) =
        retrofitClient(baseUrl, httpClient())


    private fun httpClient(): OkHttpClient {

        val httpLoggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT)
        val clientBuilder = OkHttpClient.Builder()
        if (BuildConfig.DEBUG) {
            httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            clientBuilder.addInterceptor(httpLoggingInterceptor)
        }
        clientBuilder.addInterceptor { chain ->
            val newRequest = chain.request().newBuilder()
                .addHeader( //I can't get token because there is no context here.
                    "Authorization", "Bearer ${PreferencesHelper.getInstance(context).token.toString()}"
                )
                .build()
            chain.proceed(newRequest)
        }



        clientBuilder.readTimeout(120, TimeUnit.SECONDS)
        clientBuilder.writeTimeout(120, TimeUnit.SECONDS)
        return clientBuilder.build()
    }

    private fun retrofitClient(baseUrl: String, httpClient: OkHttpClient): Retrofit =
        Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(httpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()

AppModule

val appModule = module {
    single {
        androidApplication().getSharedPreferences("PREFERENCES", android.content.Context.MODE_PRIVATE)
    }
    single { createNetworkClient(BuildConfig.BASE_URL) }
    single { (get() as Retrofit).create(Api::class.java) } 
    viewModel {
        ContactViewModel(get())
    }
}

MyContactActivity

 private val contactList: ContactViewModel  by viewModel()
    override fun onCreate(savedInstanceState: Bundle?) {
        viewModel = contactList

        super.onCreate(savedInstanceState)
        binding.adapter = ContactAdapter(this)
        binding.layoutManager = LinearLayoutManager(this)

        contactList.getContactList()

        contactList.contactListLiveData.observe(this, Observer { list ->
            if (list != null)
                binding.adapter?.update(list)
        })
    }
1 Answers

You can create a Koin module to provide the Shared Preferences:

val sharedPreferencesModule = module {

   single {
      androidApplication().getSharedPreferences("PREFERENCES",  android.content.Context.MODE_PRIVATE)
   }
}

And then inject it with Koin into the class that generates the Retrofit client.

EDIT

You need to modify your createNetworkClient method signature:

fun createNetworkClient(baseUrl: String, preferences: SharedPreferences)

And then inject it with Koin:

val appModule = module {
    single {
        androidApplication().getSharedPreferences("PREFERENCES", android.content.Context.MODE_PRIVATE)
    }
    single { createNetworkClient(BuildConfig.BASE_URL, get()) }

    ...
}

Then you will receive the Shared Preferences injected in the createNetworkClient method and just need to implement the logic to retrieve the token from the Shared Preferences.

Related