Nikiizvorski
07/15/2021, 1:45 PMoverride suspend fun waitForFix(timeoutMsec: Long, scope: CoroutineScope): Location? {
return getLocation() ?: let {
val channel = Channel<Location?>(1)
val timeout = scope.launch {
delay(timeoutMsec)
channel.send(null)
}
getUpdates { fix ->
scope.launch {
timeout.cancel()
channel.send(fix)
}
}
channel.receive()
}
}
Oliver.O
07/15/2021, 2:04 PMgetUpdates()
is blocking and does not support cancellation. If it were cancellable, you might want to use withTimeout { ... }
instead of your channel-based solution. See https://stackoverflow.com/a/47641886/2529022Nikiizvorski
07/15/2021, 2:06 PMwithTimeout(timeoutMsec) {
getUpdates { fix ->
scope.launch {
channel.trySend(fix)
}
}
channel.receive()
}
Oliver.O
07/15/2021, 5:15 PMtrySend()
is non-blocking, you can avoid the overhead of an extra coroutine:
getUpdates { channel.trySend(it) }
should do just fine.Nikiizvorski
07/15/2021, 5:16 PM