With coroutines, we can try to cancel a Job and get out of doing its work. Whether this succeeds or not depends a bit on the coroutine
b4777467766цитує2 роки тому
A variation of cancel() is cancelAndJoin(). This cancels a job, but then blocks waiting for that job to complete its cancellation process
b4777467766цитує2 роки тому
If you cancel a job, all of its child jobs get canceled as well.
b4777467766цитує2 роки тому
Note that the inverse is not true: canceling a child job does not cancel its parent.
b4777467766цитує2 роки тому
If the code in a coroutine has an unhandled exception, its job gets canceled
b4777467766цитує2 роки тому
Here, we have two independent jobs. The second job generates a NullPointerException, so it will be canceled at that point, skipping the rest of its work. The first job, though, is unaffected, since it is not related to the second job.
b4777467766цитує2 роки тому
In reality, what happens is that an unhandled exception cancels the parent job, which in turn cancels any children.
b4777467766цитує2 роки тому
Klassbook) This time, rather than the child canceling the parent directly, the child crashes with a NullPointerException. However, the effect is more or less the same as if the child job had canceled the parent: the parent job is canceled, which in turn cancels the child job.
b4777467766цитує2 роки тому
Sometimes, we need to stop long-running work because it is running too long.
For that, we can use withTimeout(). withTimeout() creates a child job, and it cancels that job if it takes too long.
b4777467766цитує2 роки тому
withTimeout() throws a TimeoutCancellationException. That exception gets handled inside of launch() by default. Since cancellation is considered a normal thing to do, the TimeoutCancellationException does not trigger a crash. However, since withTimeout() threw an exception, the rest of our code inside of launch() gets skipped.
fb2epub
Перетягніть файли сюди,
не більш ніж 5 за один раз