Can anyone please explain what `yield()` is doing?...
# coroutines
a
Can anyone please explain what
yield()
is doing?
Copy code
@Test
    fun testLaunchAndYieldJoin() = runTest {
        expect(1)
        val job = launch(coroutineContext) {
            expect(3)
            yield()
            expect(4)
        }
        expect(2)
        assertTrue(job.isActive && !job.isCompleted)
        job.join()
        assertTrue(!job.isActive && job.isCompleted)
        finish(5)
    }
a
I can't find any mention except
There are two approaches to making computation code cancellable. The first one is to periodically invoke a suspending function that checks for cancellation. There is a yield function that is a good choice for that purpose.
which I don't totally understand, is its total purpose to check if a coroutine is cancelled ?
please note it's different than the one used with
buildSequence
w
from the docs of
yield
Copy code
Yields a thread (or thread pool) of the current coroutine dispatcher to other coroutines to run. If the coroutine dispatcher does not have its own thread pool (like Unconfined dispatcher) then this function does nothing, but checks if the coroutine Job was completed. This suspending function is cancellable. If the Job of the current coroutine is cancelled or completed when this suspending function is invoked or while this function is waiting for dispatching, it resumes with CancellationException.
a
I already checked that, I was looking for more simplified answer 😄 What I understands that it's used because it's cancellable, so if the code passed it within a coroutine, this means the coroutine is still active, is this true?
w
It’s used in 2 ways. 1. To suspend the current coroutine so that other coroutines may execute. 2. to pause the current coroutine and check for cancellation
so if you have a long running task, you can use it to pause and be more cooperative, or alternatively pause to see if the coroutine has been cancelled to avoid doing unecessary work
a
Thanks
g
yield is empty suspension point, like callback that returns without waiting, right after you subscribe on it, but it helps to suspend coroutine so, as Matt mentioned, check that coroutine is cancelled or reschedule coroutine. Helpful if you have some loop that doesn’t have other suspension points, so you can just call
yield()
and have automatica cancellation support
a
got it, thanks @gildor
w
If you’re going to do looping, if possible you want to make use of the
isActive
flag, which represents whether the coroutine is still active.
👍 1