Hi ! I'm using ```coroutineScope.launch {``` in or...
# coroutines
l
Hi ! I'm using
Copy code
coroutineScope.launch {
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
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
Thank you very much ๐Ÿ™‚. That's perfect for me ๐Ÿ˜„
j
Or if using Kotlin 1.6,
withTimeout(1.minutes)
๐Ÿ™‚ (but
withTimeout(Duration)
is still experimental AFAIK even though
Duration
is stable now)
๐Ÿ‘๐Ÿพ 1
j
I guess it is caused by coroutines is not yet in 1.6
๐Ÿ†— 1