How do we generally define coroutine scope on Andr...
# android
k
How do we generally define coroutine scope on Android and on the backend? Constructing coroutine scope by @marcinmoskala https://kt.academy/article/cc-constructing-scope
g
On Android you almost always should use scope which you receive from Android Lifecycle, and for ViewModel use built in viewModelScope: https://developer.android.com/topic/libraries/architecture/coroutines
In modern Android applications, instead of defining your own scope, you can also use 
viewModelScope
I would say that it’s an option by default, and you should have a really good reason to use custom scopes
m
Well, maybe you are right for most project, because we can set test dispatcher via
setMain
, but it still limits testing capabilities a bit 🤔 Also I find it useful to set own
CoroutineExceptionHandler
. Can it be done for
viewModelScope
?
g
but it still limits testing capabilities a bit
In what sense? What is your use case for CoroutineExceptionHandler in view model? Our project is definitely not small at all, and mostly coroutines based, but we have 0 custom exception handlers
m
I've used them to define a common way to show an exception to the user (dialog/toast/snackbar), and/or to log the exception to Firebase.
Don't you define such common mechanism for exception handling?
g
No, we always do explicit error handling, if something is not handled correctly, app will crash
All automated error handling for user are usually bad in terms of UX, Sometimes you want to show error in view, sometimes on snackbar (which also requires access to view), sometimes toast is enough
m
Yes, but this typically depends on the exception type, less often on there this exception occurred, so generic exception handles are typically having some
when
that decided how to handle this (so show login view in case od 401, maybe a dialog on 500, maybe a snackbar when problems with internet connection etc.)
g
We handle 401 and re-login events on level of http client, not on level of UI code
Also all those cases could be just handled by calling some handler function in catch explicitly