Marc Knaup
05/26/2020, 9:17 AMsessionCoroutineContext
that gets canceled once the user has logged out (i.e. the session is closed).
I have a MessageRepository
that must only be used while the session is open.
Do I now have to wrap every single suspend fun
in my MessageRepository
with withContext(sessionCoroutineContext) { … }
so that they cancel once the session is closed?
Some context:
I still have a scenario where an Android activity is collecting a flow in its viewModelScope
.
An element is collected after the user’s session was closed.
The collector uses the repository which in turn uses the database which in turn tries to access files that no longer exist because the session is closed -> boom.
The idea is to have repository and database properly bound to the session lifecycle so that it doesn’t even try to do anything when the session is gone and throws a cancellation up to the collector.henrikhorbovyi
05/26/2020, 4:05 PMsuspend fun
with withContext(sesstionCoroutineContext)
viewModelScope.launch {
// on main dispatcher
withContext(sesstionContext) {
// running on your own dispatcher
messageRepository.doYourStuff()
}
}
<<<
Every function called from your MessageRepository
will "inherit" your sessionCoroutineContext
Marc Knaup
05/27/2020, 7:20 AMwithContext
. That adds even more noise than wrapping all function implementations.
Let’s say I would at one point decide to extend or shrink the repository’s lifecycle a little, i.e. use another context object. I would have to modify every single call site.