Hi! What would be a cold equivalent of RxJava's `...
# coroutines
d
Hi! What would be a cold equivalent of RxJava's
Single
in coroutines? for example
Single.fromCallable { doNetworkRequest() }
would emit only upon subscription. Should I just use
Flow
which calls a suspending function inside? or is this too complex?
OK, I think the
Copy code
scope.launch { doNetworkRequest() }
Is actually conceptually the same as
Single.fromCallable
t
launch
is hot. The conceptually closest to
Single
is the following :
Copy code
scope.async(start = CoroutineStart.LAZY) { doNetworkRequest() }
Note that you have to call
deferred.await()
to trigger computation
d
oh, thanks. I remember reading about this construct, but for some reason I thought it must be manually started with
.start()
didn't know that awaiting would start it too. Missed it, it's actually mentioned in docs
e
The closest concept to Rx
Single
is a simple suspending function. It would “emit” (do something) only when you call it.
☝️ 6
Don’t use flow or anything more complicated for that. All this complexity is not needed in Kotlin.
d
OK, so basically the solution is to delay suspending function call up until to the point where it's needed. For example where in Rx I would return
Single<>
for consumers, now I return
suspend fun
and do this transitively through all app layers up to the point (e.g in UI) where in Rx I would call
subscribe()
, but now I call
launch()
e
You don’t need to “return Single” anymore. Whenever you’ve declared
fun foo(): Single<T>
you now declare
suspend fun foo(): T
which your consumers call when they need.
It vastly simplifies all the code, both implementation and use-site.
👌 4
d
That's what I meant. Tried to draw an analogy between my Rx-thinking and Coroutine thinking 🙂
e
Indeed,
subscribe
gets replaced with
launch
. It is the correct analogy.
d
Thank you! So far I really like using coroutines (started learning recently hence silly questions).