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

dharrigan

10/04/2019, 8:36 AM
Copy code
fun updateDetails() = GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
    // loop forever
    updateDetailsAsync()
    // wait until updateDetailsAsync is done
}

fun CoroutineScope.updateDetailsAsync() {
    does an REST API lookup
    writes into a database
}
s

spand

10/04/2019, 8:50 AM
Why doesnt a
while (true)
loop cut it?
d

dharrigan

10/04/2019, 8:52 AM
That's what I thought about doing...but I wanted to know if there was a kotlin/coroutine way
more idomatic with using coroutines
I suppose this will do:
s

spand

10/04/2019, 8:56 AM
A key design feature of coroutines is that sequential stuff looks and acts the same as in "normal" kotlin
d

dharrigan

10/04/2019, 8:56 AM
Copy code
do {
updateDetailsAsync()
delay(MINUTES.toMillis(1))
} while (true)
Thanks Johannes! 🙂
I suppose another way is for the
CoroutineScope.updateDetailsAsync()
to return a Job, then join on the job
s

spand

10/04/2019, 8:59 AM
Or just make it
suspend
?
d

dharrigan

10/04/2019, 8:59 AM
great!
d

Dominaezzz

10/04/2019, 10:26 AM
Perhaps
while(isActive)
is a bit better.
3
s

spand

10/04/2019, 10:44 AM
Why ?
d

Dominaezzz

10/04/2019, 10:47 AM
It allows for cancellation if need be.
s

spand

10/04/2019, 10:53 AM
So does calling a
suspend
function no ?
d

Dominaezzz

10/04/2019, 11:02 AM
Yes your code allows for cancellation as it is but you asked for idiomatic.
👍 1
d

dharrigan

10/05/2019, 12:39 PM
ta! 🙂
2 Views