https://kotlinlang.org logo
Title
n

Norbi

02/13/2023, 6:12 PM
Is it correct to use
yield()
for interfacing non-blocking functions from an external library? Like this example code:
while (...) {
    val r: Int = nonBlockingFunction() // Returns -1 if no data available
    if (r == -1) {
        yield() // Is this a correct way to "wait" in the coroutine?
    } else {
        ... // Do something with the data
    }
}
e

ephemient

02/13/2023, 6:20 PM
while (true) yield()
will allow other coroutines to run, but it always returns to the back of the runqueue so you'll spin 100% of CPU doing it. in general, I would not call that "correct"
n

Norbi

02/13/2023, 7:07 PM
I see... what do you recommend? Calling
delay(x)
instead does not seem "reactive" enough.
e

ephemient

02/13/2023, 7:10 PM
a non-blocking API must have some way to notify you when it's actually ready