• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
<lambda>null2  * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 package kotlinx.coroutines
6 
7 import kotlin.coroutines.*
8 import kotlin.coroutines.intrinsics.*
9 
10 /**
11  * Yields a thread (or thread pool) of the current coroutine dispatcher to other coroutines to run.
12  * If the coroutine dispatcher does not have its own thread pool (like [Dispatchers.Unconfined]) then this
13  * function does nothing, but checks if the coroutine [Job] was completed.
14  * This suspending function is cancellable.
15  * If the [Job] of the current coroutine is cancelled or completed when this suspending function is invoked or while
16  * this function is waiting for dispatching, it resumes with [CancellationException].
17  */
18 public suspend fun yield(): Unit = suspendCoroutineUninterceptedOrReturn sc@ { uCont ->
19     val context = uCont.context
20     context.checkCompletion()
21     val cont = uCont.intercepted() as? DispatchedContinuation<Unit> ?: return@sc Unit
22     if (!cont.dispatcher.isDispatchNeeded(context)) {
23         return@sc if (cont.yieldUndispatched()) COROUTINE_SUSPENDED else Unit
24     }
25     cont.dispatchYield(Unit)
26     COROUTINE_SUSPENDED
27 }
28 
checkCompletionnull29 internal fun CoroutineContext.checkCompletion() {
30     val job = get(Job)
31     if (job != null && !job.isActive) throw job.getCancellationException()
32 }
33