I use Koin
with Jetpack Compose
. I have to create a custom scope for one of my ViewModels
as it should stay alive as long as the user is logged in.
I tried to do that in my composable, wrapping it in rememberSaveable
and creating a custom Saver
for that scope, but on every configuration change a new instance of my Scope
was created. So I used one of my ViewModels
as a holder for that scope. That ViewModel
is single, so there is nothing to worry about.
The module:
val MY_MODULE = module {
scope(named(LOGGED_IN_SCOPE)) {
scopedOf(::MyViewModel)
}
}
In the ViewModel, where I handle the scope creation, I have these methods:
private val _loggedInScope: MutableStateFlow<Scope?> = MutableStateFlow(null)
val loggedInScope: StateFlow<Scope?> = _loggedInScope.asStateFlow()
fun createLoggedInScope() {
if (_loggedInScope.value != null) return
val koin = KoinPlatformTools.defaultContext().getOrNull() ?: return
_loggedInScope.update {
koin.getOrCreateScope(LOGGED_IN_SCOPE_ID, named(LOGGED_IN_SCOPE))
}
}
fun closeLoggedInScope() {
_loggedInScope.value?.close()
_loggedInScope.value = null
}
I collect that flow in one of my composables
and when the user logs in, I pass that scope to another composable, where I inject my ViewModel
like this:
val myViewModel by loggedInScope.inject<MyViewModel>()
When the user logs out, I call closeLoggedInScope
, but the onCleared
in MyViewModel
is not being triggered. Does it have something to do with Koin’s scopes? Thank you.