Home > OS >  How to work withTimeout in Coroutine on Android
How to work withTimeout in Coroutine on Android

Time:02-06

In my application I want use Coroutines and I write simple code for check withTimeout function!
I write below codes, and I think after 3sec stop my working and show me Done message!
But after 3sec stop coroutines but not show me done message!

My Codes :

CoroutineScope(Default).launch {
    Log.e(TAG, "Start coroutine")
    withTimeout(3000) {
        for (i in 20..50) {
            if (isActive) {
                delay(500)
                Log.e(TAG, "Show i => $i")
            }
        }
    }
    Log.e(TAG, "Done coroutine")
}

Logcat messages :

2022-02-05 18:08:11.891 12413-12484/my.app.coroutines E/CoroutinesTag: Start coroutine
2022-02-05 18:08:12.399 12413-12484/my.app.coroutines E/CoroutinesTag: Show i => 20
2022-02-05 18:08:12.900 12413-12485/my.app.coroutines E/CoroutinesTag: Show i => 21
2022-02-05 18:08:13.404 12413-12491/my.app.coroutines E/CoroutinesTag: Show i => 22
2022-02-05 18:08:13.905 12413-12486/my.app.coroutines E/CoroutinesTag: Show i => 23
2022-02-05 18:08:14.406 12413-12491/my.app.coroutines E/CoroutinesTag: Show i => 24

Why not show me done (Done coroutine) message?

CodePudding user response:

description for withTimeout

Runs a given suspending block of code inside a coroutine with a specified timeout timeMillis and throws a TimeoutCancellationException if the timeout was exceeded.

TimeoutCancellationException extends CancellationException which is used for exiting a builder function like launch gracefully. If you don't want your job to finish you can use withTimeoutOrNull

And from the official docs

The TimeoutCancellationException that is thrown by withTimeout is a subclass of CancellationException. We have not seen its stack trace printed on the console before. That is because inside a cancelled coroutine CancellationException is considered to be a normal reason for coroutine completion. However, in this example we have used withTimeout right inside the main function.

Since cancellation is just an exception, all resources are closed in the usual way. You can wrap the code with timeout in a try {...} catch (e: TimeoutCancellationException) {...} block if you need to do some additional action specifically on any kind of timeout or use the withTimeoutOrNull function that is similar to withTimeout but returns null on timeout instead of throwing an exception:

  •  Tags:  
  • Related