https://kotlinlang.org logo
Title
i

Ive Vasiljevic

08/26/2019, 6:11 PM
How would I convert this behavior into coroutines?
d

Dominaezzz

08/26/2019, 6:12 PM
GlobalScope.launch(Dispatchers.Main) {
    delay(1500)
    currentSpeedText.text = "${speedService.acquireSpeed().roundToNDecimalPlaces(1)} km/h"
}
i

Ive Vasiljevic

08/26/2019, 6:13 PM
Why GlobalScope and not CoroutineScope?
d

Dominaezzz

08/26/2019, 6:14 PM
You can (and should) use a more specific scope, like some activity scope or view model scope but without context of where this code is going to run
GlobalScope
is most accurate.
The behaviour is the same anyway.
i

Ive Vasiljevic

08/26/2019, 6:26 PM
How would I run this coroutine indefinitely over and over again?
Until I say it to stop
similar to handler.removeCallbacks()
s

streetsofboston

08/26/2019, 6:42 PM
val job = scope.launch(Dispatchers.Main) {
    while (true) {
        delay(1500)
        currentSpeedText.text = "${speedService.acquireSpeed().roundToNDecimalPlaces(1)} km/h"
    }
}

...

// either this
job.cancel() // cancels the `launch` only
// or this
scope.cancel() // cancels the `launch` and the ends the scope.
r

reline

08/26/2019, 7:05 PM
@streetsofboston I believe you should be using
while (isActive)
instead of
while (true)
here or your job will continue even after being cancelled.
s

streetsofboston

08/26/2019, 7:06 PM
The call to
delay
will throw a CancelationException when
job.cancel()
(or
scope.cancel()
) is called and your Coroutine ends properly.
d

Dominaezzz

08/26/2019, 7:06 PM
Since
delay
is used, it's fine.
r

reline

08/26/2019, 7:07 PM
ah 🤦‍♂️
d

Dominaezzz

08/26/2019, 7:07 PM
Although I do agree that
isActive
should be used anyway.
s

streetsofboston

08/26/2019, 7:07 PM
If you have long-running blocking code (not suspending code), then calling
ensureActive()
or
isActive
(here and there) is a good way to go.
d

Dominaezzz

08/26/2019, 7:08 PM
ensureActive()
and
isActive
is not really available in non-suspending code.
Unless you actually mean blocking, then cancellation simply isn't possible.
g

gildor

08/27/2019, 1:30 AM
isActive is not suspend, so it’s not a problem to use it in non-suspending code
actually mean blocking, then cancellation simply isn’t possible
It’s possible if you can split this blocking invocation to multiple steps, like when you read/write to stream, when. So it really depends on nature of this blocking operation, sometimes you just have some cancellation handle even for blocking operation