Seri
09/13/2024, 5:27 PMSeri
09/13/2024, 5:28 PMUserSession
. When a session is closed, all of those resources should be cleaned up. When one is opened, they should be recreated. I believe this is a good way to create the scopes for this purpose:
val sessionModule = module {
single<SessionManager> {
SessionManager()
}
scope<AuthenticatedSession> {
scopedOf(::AuthenticatedSession)
}
}
Seri
09/13/2024, 5:29 PMval androidModule = module {
scope<AuthenticatedSession> {
viewModel<AuthenticatedViewModel> {
AuthenticatedViewModel(session = get())
}
}
viewModel<UnauthenticatedViewModel> {
UnauthenticatedViewModel(sessionManager = get())
}
}
Seri
09/13/2024, 5:30 PMSessionManager.kt
class SessionManager {
var session: AuthenticatedSession? = null
fun login() {
session?.logout()
session = AuthenticatedSession()
}
fun logout() {
session?.logout()
session = null
}
}
AuthenticatedSession.kt
class AuthenticatedSession : KoinScopeComponent {
override val scope: Scope by lazy { createScope(this) }
val userId = Random.nextInt().toString()
val logger = getKoin().logger
init {
<http://logger.info|logger.info>("AuthenticatedSession created: $userId")
}
fun logout() {
<http://logger.info|logger.info>("AuthenticatedSession close: $userId")
scope.close()
}
}
Seri
09/13/2024, 5:33 PMSessionManager.login()
from a viewmodel, two sessions with different ID's appear to be created.
2024-09-13 12:33:20.677 9004-9004 [Koin] dev.seri.kointests.android I AuthenticatedSession close: -1128270103
2024-09-13 12:33:20.679 9004-9004 [Koin] dev.seri.kointests.android I AuthenticatedSession created: 1187421452
Seri
09/13/2024, 5:35 PMScope.koinViewModel
method, similar to the plain koinViewModel
. When I inject this way, I appear to be recreating several instances of the ViewModel, rather than reusing the same one.
authenticatedViewModel: AuthenticatedViewModel = session.get<AuthenticatedViewModel>()
Seri
09/13/2024, 6:44 PMscopedOf(::AuthenticatedSession)
in my sessionModule. This definition is unnecessary, and ended up created a new scope-of-a-scope field.
Solution #2
• When using koinViewModel()
to create a scoped viewModel, simply pass in the scope to resolve from.Seri
09/17/2024, 2:58 PM