Hello everyone! :wave: Is there some best practic...
# flow
m
Hello everyone! 👋 Is there some best practice for using flow to get only one item? Like alternative Single in Rx, when I guaranteed want to get single value and not ready to process stream.
w
Yes, a suspendable function returning an object 🙂
😊 1
m
Yes I understand it. But I thought using all capabilities of Flow (operators etc) and at the same time be sure that I will get only one value, like Single observable in Rx.
w
If you have a stream of values and in the end want only one, you can use operators like
single()
or
first()
. However, if there’s just one value, and you’d use
Single<T>
in RxJava, then idiomatic coroutines equivalent is a
suspend fun
. Do you have some specific example where you’d like to use a potential
SingleFlow
with operators?
m
you can use operators like 
single()
 or 
first()
.
For now i’m trying to use
take(1)
for it.
Do you have some specific example where you’d like to use a potential 
SingleFlow
 with operators?
There is no any specific example. It’s all common cases like Basically, I don’t like combining two approaches in project. Like this:
Copy code
interface A {
    fun foo(): Flow<String>
    suspend bar(): String
}
Because I will need to process them a little differently.
w
Then I can only suggest that you reconsider — these two approaches represent very different things, and so a different approach is expected. IMO operating on a suspendable function doesn’t add any complexity to the project, because most of the time the code is written like a regular imperative code. All in all suspendable functions are less complex than flows, and they are designed for the case when you asynchronously get a single value. Using Flow for that, unless you expect to get more values in the future, is just not idiomatic Kotlin
m
Thank you, Łukasz
👍 1
p
At the start of the year we were faced with the decision of migrating from RxJava2 ➡️ RxJava3, or, switch to coroutines/Flow. It was a conceptual leap to go from
Completable
and
Single
over to suspending functions and a few of our dyed-in-the-wool Rx folk were skeptical, but we all now agree that it was well worth the effort - code greatly simplified and testing was much easier. I think the biggest “aha!” / “Ohh, shiny!” moment came when we discovered suspending lambdas 😉
m
Thanks a lot for sharing, Paul! So you are using now both coroutines and Flow, right? As for me, the most strange thing at the moment is that we gonna use different approach for single and multiply operations. Flow is higher level tool, build upon coroutines and uses FP like approach, while coroutines more low level tool, with imperative approach. I am afraid that many people could build their own Single wrappers over Flow.