9

I'm trying to create a user scope using Koin. When the user is logged, I'm creating the scope :

val scope = getKoin().createScope("USER_SCOPE")

And when the user clicks on logout, I'm destroying the scope

    scope?.let {userScope ->
        userScope.close()
        getKoin().deleteScope(userScope.id)
    }

In my koin module, I have a scoped UserRepository which should live only during the user session. I also have ViewModels and Use Cases which are using this repository, and I try to inject the scoped repo inside them

val appModule = module {
    scoped<UserRepository> { UserDataRepository() }
    viewModel { UserViewModel(getScope("USER_SCOPE").get()) }
    factory { MyUseCase(getScope("USER_SCOPE").get()) }
}

On the first login, it is working normally, I have my user repo injected in my viewmodel and use case. But after a logout (which is deleting the scope) and after another login, the UserRepository instance is still exactly the same.

Do I miss something in the scope usage ?

Mathieu H.
  • 800
  • 8
  • 21

1 Answers1

10

Migrating from koin 2.0.0-rc-2 to koin 2.0.0-GA solved my problem.

After migrating, it is not possible to declare a scoped instance outside a scope. So I adapted my appmodule this way :

   val appModule = module {
        scope(named("USER_SCOPE")) {
            scoped<UserRepository> { UserDataRepository() }
        }
        viewModel { UserViewModel(getScope("USER_SCOPE").get()) }
        factory { MyUseCase(getScope("USER_SCOPE").get()) }
    }

Scope declaration is also a bit different :

val scope = getKoin().createScope("USER_SCOPE", named("USER_SCOPE"))

This way I have my UserRepository recreated after a logout/login.

Mathieu H.
  • 800
  • 8
  • 21