gregd
05/13/2020, 2:47 PMCoroutineScope
.
I have a pretty standard Android architecture: ViewModel, Repository, DataSource & API layers.
I want to pass ViewModel.viewModelScope
from the ViewModel to the API layer, BUT I don’t need it in the intermediate layers (Repo & DS). What do I do?
First thing that comes to my mind is marking all in-between functions with suspend
, which would pass the Scope implicitly.
But according to @elizarov we should only mark the function with suspend
if it’s really going to suspend, and those intermediate layers definitely won’t.
So, is there a better way? Is there a proper way? How do you do it?Zach Klippenstein (he/him) [MOD]
05/13/2020, 2:53 PMbezrukov
05/13/2020, 2:53 PMand those intermediate layers definitely won’t.Why? Since they will call API (which is suspend), they will be suspend too
gregd
05/13/2020, 2:57 PMgregd
05/13/2020, 2:57 PMclass MyRepository {
fun handleIncomingRequest(request: Request)
fun setOutgoingRequestListener(listener: (Request) -> Unit)
}
gregd
05/13/2020, 2:58 PMgregd
05/13/2020, 3:01 PMZach Klippenstein (he/him) [MOD]
05/13/2020, 3:15 PMgregd
05/13/2020, 4:41 PMchannelFlow
)... Meanwhile, callback version is as easy as it gets - you pass a Request one way, and Listener the other way… Can you share a simple Flow-based example?Zach Klippenstein (he/him) [MOD]
05/13/2020, 5:13 PMchannelFlow
is "really weird", it's the primary API to create Flows that from callbacks and concurrent sources.
Anyway, I'm not saying callbacks are necessarily inherently bad. But to answer your original question, the reason it seems weird that you have to explicitly pass coroutine contexts/scopes around is because you're jumping between different models of expressing asynchrony (coroutines to callbacks and then back to coroutines). If your layers were consistent, then either you wouldn't need to pass scopes around at all (if everything's callback based) or scopes would automatically get passed around (if everything's coroutines).
That said, while callbacks are "simpler" in that they involve less code, they also address fewer issues. I.e. error handling, accidentally leaking callbacks, backpressure, are all things you need to solve manually when using callbacks, whereas coroutines have already thought of all this and handle it mostly automatically.gregd
05/13/2020, 5:39 PMConflatedBroadcastChannel
etc. Especially Compared to those couple of lines of callbacks, right? So I hope someday I’ll find an easy way, but untill then I’ll probably mark my functions as suspend
and keep the code as is.gregd
05/13/2020, 5:42 PMStateFlow
looks promising. Not sure if that’s the right direction, but definitely worth trying.gildor
05/14/2020, 2:33 AM