Hi everyone, what is good practice for remote data...
# coroutines
r
Hi everyone, what is good practice for remote data sources w.r.t. coroutine scope? Should they have some parent scope injected that they use directly? Create their own "narrower" scope from? Do nothing with scope and only expose suspending functions?
c
The main purpose of
CoroutineScope
is to provide a lifetime during which coroutine operations can execute, so when thinking about how coroutineScopes relate to remote data sources, the question naturally becomes: what is the lifetime of the remote connection? And what would you hope to gain by creating your own coroutineScope rather than exposing suspend functions or flows, thus delegating the lifetime of the remote connection to something like
viewModelScope
whose lifetime you don’t have to manage yourself?
r
Excellent points. Thinking about it more it doesn't really make sense for my remote connection to live longer than the screen where the data are displayed, in which case tying it to the same lifecycle as the view model for a screen or composable on that screen would make sense. Then at that point I don't need to worry about creating a new scope etc, just exposing suspend functions and letting the caller of my data source API (e.g. a view model through a repository) manage the scope.
s
Typically they should expose suspend functions. In some scenarios it might make sense to inject an app level scope. Source: https://developer.android.com/kotlin/coroutines/coroutines-best-practices
p
Is it hot (actively does work by itself) or cold (callers do the work)? I usually favor cold for testability and simplicity when in doubt
r
@Patrick Steiger Cold, work will be triggered by some input from the UI e.g. navigation to a screen or button click. @stojan thanks for the link, Ill read through it