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

Ruckus

10/12/2018, 4:54 PM
If you use a different scope for
launch
(like
GlobalScope
) your code will work without
yield
.
m

marcinmoskala

10/12/2018, 5:06 PM
Also default dispatcher helps:
Copy code
fun main(args: Array<String>) = runBlocking<Unit>(Dispatchers.Default) {
    val job = launch {
        var nextPrintTime = System.currentTimeMillis() + 500
        while (isActive) {
            if(System.currentTimeMillis() > nextPrintTime) {
                println("World!")
                nextPrintTime += 1000
            }
        }
    }
    println("Hello,")
    delay(2000)
    job.cancelAndJoin()
    println("World")
}
or:
Copy code
fun main(args: Array<String>) = runBlocking<Unit> {
    val job = launch(Dispatchers.Default) {
        var nextPrintTime = System.currentTimeMillis() + 500
        while (isActive) {
            if(System.currentTimeMillis() > nextPrintTime) {
                println("World!")
                nextPrintTime += 1000
            }
        }
    }
    println("Hello,")
    delay(2000)
    job.cancelAndJoin()
    println("World")
}
@antonkeks It looks like a good puzzler to me 😉
g

gildor

10/13/2018, 3:18 AM
while(true)
blocks the only available thread, doesn’t look as puzzler for me
But interesting that it worked before, because launch was global and not child of runBlocking
3 Views