Ive Vasiljevic
08/26/2019, 6:11 PMDominaezzz
08/26/2019, 6:12 PMGlobalScope.launch(Dispatchers.Main) {
delay(1500)
currentSpeedText.text = "${speedService.acquireSpeed().roundToNDecimalPlaces(1)} km/h"
}
Ive Vasiljevic
08/26/2019, 6:13 PMDominaezzz
08/26/2019, 6:14 PMGlobalScope
is most accurate.Ive Vasiljevic
08/26/2019, 6:26 PMstreetsofboston
08/26/2019, 6:42 PMval 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.
reline
08/26/2019, 7:05 PMwhile (isActive)
instead of while (true)
here or your job will continue even after being cancelled.streetsofboston
08/26/2019, 7:06 PMdelay
will throw a CancelationException when job.cancel()
(or scope.cancel()
) is called and your Coroutine ends properly.Dominaezzz
08/26/2019, 7:06 PMdelay
is used, it's fine.reline
08/26/2019, 7:07 PMDominaezzz
08/26/2019, 7:07 PMisActive
should be used anyway.streetsofboston
08/26/2019, 7:07 PMensureActive()
or isActive
(here and there) is a good way to go.Dominaezzz
08/26/2019, 7:08 PMensureActive()
and isActive
is not really available in non-suspending code.gildor
08/27/2019, 1:30 AMactually mean blocking, then cancellation simply isn’t possibleIt’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