https://kotlinlang.org logo
#coroutines
Title
# coroutines
b

Ben Butterworth

02/02/2021, 6:15 PM
Should functions (e.g. in ViewModel or even Service) select the context (
withContext(context)
or
async(context) {}
)
and return
Deferred
, or should callers have the responsibility to select the context? I would think its cleaner to encapsulate the context choice to a lower level function itself. Fragment/Activity calls ViewModel calls Service calls API. The Service returns a
Result<T>
, and I originally made ViewModel functions return
Deferred<T>
, so Fragments need to
await
it. However, I found lots of examples calling
async {}
everywhere the functions are called, so callers need to know which context to use, which they will likely know less than the API designer. Also, the
withContext
coroutine function seems to imply people should be calling it in fragments/ highest level. I assume this because
withContext
seems ‘terminal’ (it suspends until it completes). I am still working on my coroutine understanding, so I would appreciate any help 🙂
Or maybe not
d

Dominaezzz

02/02/2021, 6:25 PM
Context should be chosen by the code that is most aware of context needs to be used. So the service should do so.
b

Ben Butterworth

02/02/2021, 6:25 PM
oh excellent, thank you!
Sorry i have confused myself. its not the context selection, but the scope selection. I guess i should be reducing the amount of nested scopes, so only the highest caller should create one.
u

uli

02/03/2021, 11:09 PM
And why do you use async/Deferred instead of just suspend functions?
b

Ben Butterworth

02/05/2021, 9:54 AM
so that the highest level caller (fragment/ activity/ controller) doesn’t have to error handling. Then again, we do have lifecycleScope, so what I’ve done now is launch coroutine and subsequent error handling in the fragment. I don’t like this because a caller of the same function from another activity will need to duplicate code. So in the end, I think its right to believe some error handling should be handling by the fragments/activities, not the view model, since this could affect the UI.
7 Views