Search code examples
androidkotlindependency-injectionkoin

Koin DI Clear dependencies


I am passing the token to the GET method of the request using Koin. But after authorizing a new user, the old token is saved. To get a new access token, you need to exit the application, log in again and log in.

How do I get the Koin dependencies to be cleared when the Logout button is clicked?

val appModule = module {

    factory { provideToken(provideSharedPreferences(androidContext())) }
}

private fun provideSharedPreferences(context: Context): SharedPreferences =
    context.getSharedPreferences("token", Context.MODE_PRIVATE)

fun provideToken(sharedPreferences: SharedPreferences): String =
    sharedPreferences.getString("key", "")

Inject token:

class VkRetrofitDataSource (
    private val vkRetrofitApi: VkRetrofitApi,
    private val ioDispatcher: CoroutineDispatcher,
) : VkNetworkDataSource, KoinComponent {

    private val accessToken: String by inject()

    override suspend fun getUserInfo(
        fields: String,
        apiVersion: String
    ): Result<ResponseResultUser> =
        withContext(ioDispatcher) {
                val response = vkRetrofitApi.getUserInfo(fields, apiVersion, accessToken)
                val userResponse = response.body()
                Timber.d("Token $userResponse")
                return@withContext if (response.isSuccessful && userResponse != null) {
                    Result.Success(userResponse)
                } 
}

Solution

  • I think what you need is

    private val accessToken: String get() = get() 
    

    So, every time you access this property, it will invoke that factory in Koin module