Should functions (e.g. in ViewModel or even Servic...
# coroutines
b
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
Context should be chosen by the code that is most aware of context needs to be used. So the service should do so.
b
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
And why do you use async/Deferred instead of just suspend functions?
b
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.