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

dimsuz

01/28/2020, 11:51 AM
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

tseisel

01/28/2020, 12:25 PM
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

dimsuz

01/28/2020, 12:36 PM
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

elizarov

01/28/2020, 12:45 PM
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

dimsuz

01/28/2020, 12:52 PM
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

elizarov

01/28/2020, 12:55 PM
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

dimsuz

01/28/2020, 12:56 PM
That's what I meant. Tried to draw an analogy between my Rx-thinking and Coroutine thinking 🙂
e

elizarov

01/28/2020, 12:56 PM
Indeed,
subscribe
gets replaced with
launch
. It is the correct analogy.
d

dimsuz

01/28/2020, 12:57 PM
Thank you! So far I really like using coroutines (started learning recently hence silly questions).
3 Views