https://kotlinlang.org logo
Title
r

rmyhal

03/19/2021, 9:32 AM
Hello, is there a something like
withTimeout(time) { operation }
but without canceling the operation? What I want to achieve: If an operation takes longer than
N
millis I want to have a callback about this and I want the operation to continue working. Something like:
withTime(
    time = 500L, 
    block = { operation }, 
    onTimeOver = {  }
)
c

christophsturm

03/19/2021, 9:58 AM
s

streetsofboston

03/19/2021, 11:20 AM
What about wrapping the withTimeout in a try catch block? Catch the CancellationException (and call your callback from there).
r

rmyhal

03/19/2021, 12:30 PM
@streetsofboston tried this already. But the operation(network call) inside
withTimeout
is getting cancelled when timeout passes and I lose my results
u

ursus

03/19/2021, 12:35 PM
sounds like you want multiple emits, ie. Flow
merge(yourAction, timer(x))
c

christophsturm

03/19/2021, 12:36 PM
what about
launch { delay(500); callTimer()}
r

rmyhal

03/19/2021, 2:02 PM
Tried something like this:
launch {
    val job = launch {
        // doing some long operation
    }.apply {  start() }
    delay(N)
    if (!job.isCompleted) {
        // operation took longer than N millis. 
    }
}
And looks like it’s what I wanted. Thanks