I’m still at war with scopes and contexts :sweat_s...
# coroutines
m
I’m still at war with scopes and contexts 😅 Let’s say I have a
sessionCoroutineContext
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.
h
No, you don't need to wrap all your
suspend fun
with
withContext(sesstionCoroutineContext)
Once you do >>>
Copy code
viewModelScope.launch { 
    // on main dispatcher
    withContext(sesstionContext) {
        // running on your own dispatcher
        messageRepository.doYourStuff()
    }
}
<<< Every function called from your
MessageRepository
will "inherit" your
sessionCoroutineContext
m
While that would be possible, I see the context in which the repository’s code is executed as an implementation detail. The call site shouldn’t need to know the context nor do I want to wrap a large amount of call sites with
withContext
. 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.
It also behaves differently when it comes to cancelation. See this thread: https://kotlinlang.slack.com/archives/C1CFAFJSK/p1590485497391400