I'm trying to figure out how to make this lazy (or...
# coroutines
r
I'm trying to figure out how to make this lazy (or is it already? Doesn't look like it, or does
emit
block?)
Copy code
fun getSearchResultFlow(
    api: SearchApi,
    query: String,
    pageSize: Int = 50
): Flow<Result> = flow {
    var offset = 0
    var hasMore = true

    while (hasMore) {
        val results = api.search(query, offset, pageSize)
        results.forEach { emit(it) }
        
        offset += pageSize
        hasMore = results.size == pageSize
    }
}
It's a small piece of code which iterates over a paginated list, so I can access as much as I need to.
s
Looks good to me 👍
k
emit doesn’t block, it suspends. This is indeed lazy. Flows are generally pull based unless you have an intermediary buffer of some sort like a channel
So, emit will suspend until there’s a collector to accept the element being emitted
Basically, the entire concept of backpressure keeps you from eagerly producing the elements you don’t want.
r
Err, I was using block and suspend interchangeably, coming from Scala/Haskell, where blocking doesn't really exist 😶‍🌫️
👍 1
Thanks for the help
d
from Scala/Haskell, where blocking doesn't really exist
Well, that's a provocative take!
Scala
It literally has a function called "blocking" (https://www.scala-lang.org/api/current/scala/concurrent.html#blocking-fffff7d2) to signify that this code is about to block and new threads need to be spawned.
Haskell
This feels closer to the truth, but still inaccurate when bound threads come into play: https://hackage.haskell.org/package/base-4.20.0.1/docs/Control-Concurrent.html#g:8
K 1
r
Lemme rephrase then, if you're building your off-the-mill code, it's mostly abstracted from you - in Scala, if you're working in the functional space, and less on the Java side, in Haskell I've worked with it for a few years and never encountered bound threads, so rather specific which layer you use. I've never heard of bound threads until now TBH.