https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

amrelmasry

08/06/2018, 7:35 PM
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

amrelmasry

08/06/2018, 7:52 PM
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

withoutclass

08/06/2018, 7:56 PM
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

amrelmasry

08/06/2018, 8:01 PM
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

withoutclass

08/06/2018, 8:03 PM
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

amrelmasry

08/06/2018, 9:28 PM
Thanks
g

gildor

08/07/2018, 1:22 AM
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

amrelmasry

08/07/2018, 12:13 PM
got it, thanks @gildor
w

withoutclass

08/07/2018, 4:15 PM
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
4 Views