in order to start a coroutine in my code. But is there a variant of
launch
which runs the coroutine for a given amount of time, instead of infinitely ? Because otherwise, I'm afraid my code, which is a bit a kind of spaghetti as now, will be worse.
b
bezrukov
11/18/2021, 12:33 PM
no there is no such coroutine builder, but you can wrap launch body into `withTimeout`/`withTimeoutOrNull`:
Copy code
scope.launch {
withTimeout(60_000) {
// code here will be cancelled after 1 minute
}
}
👍🏾 1
l
loloof64
11/18/2021, 12:45 PM
Thank you very much 🙂. That's perfect for me 😄
j
Joffrey
11/18/2021, 2:00 PM
Or if using Kotlin 1.6,
withTimeout(1.minutes)
🙂 (but
withTimeout(Duration)
is still experimental AFAIK even though
Duration
is stable now)
👍🏾 1
j
Javier
11/18/2021, 3:35 PM
I guess it is caused by coroutines is not yet in 1.6