How would I convert this behavior into coroutines?
# coroutines
i
How would I convert this behavior into coroutines?
d
Copy code
GlobalScope.launch(Dispatchers.Main) {
    delay(1500)
    currentSpeedText.text = "${speedService.acquireSpeed().roundToNDecimalPlaces(1)} km/h"
}
i
Why GlobalScope and not CoroutineScope?
d
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
How would I run this coroutine indefinitely over and over again?
Until I say it to stop
similar to handler.removeCallbacks()
s
Copy code
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
@streetsofboston I believe you should be using
while (isActive)
instead of
while (true)
here or your job will continue even after being cancelled.
s
The call to
delay
will throw a CancelationException when
job.cancel()
(or
scope.cancel()
) is called and your Coroutine ends properly.
d
Since
delay
is used, it's fine.
r
ah 🤦‍♂️
d
Although I do agree that
isActive
should be used anyway.
s
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
ensureActive()
and
isActive
is not really available in non-suspending code.
Unless you actually mean blocking, then cancellation simply isn't possible.
g
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