Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2016-2017 JetBrains s.r.o. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
Roman Elizarov | d528e3e | 2017-01-23 15:40:05 +0300 | [diff] [blame] | 17 | package kotlinx.coroutines.experimental |
| 18 | |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame^] | 19 | import kotlin.coroutines.experimental.intrinsics.COROUTINE_SUSPENDED |
| 20 | import kotlin.coroutines.experimental.intrinsics.suspendCoroutineOrReturn |
| 21 | |
Roman Elizarov | d528e3e | 2017-01-23 15:40:05 +0300 | [diff] [blame] | 22 | /** |
| 23 | * Yields a thread (or thread pool) of the current coroutine dispatcher to other coroutines to run. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 24 | * If the coroutine dispatcher does not have its own thread pool (like [Unconfined] dispatcher) then this |
Roman Elizarov | e727cee | 2017-01-31 09:20:36 +0300 | [diff] [blame] | 25 | * function does nothing, but checks if the coroutine [Job] was completed. |
Roman Elizarov | d528e3e | 2017-01-23 15:40:05 +0300 | [diff] [blame] | 26 | * This suspending function is cancellable. |
Roman Elizarov | e727cee | 2017-01-31 09:20:36 +0300 | [diff] [blame] | 27 | * If the [Job] of the current coroutine is completed when this suspending function is invoked or while |
| 28 | * this function is waiting for dispatching, it resumes with [CancellationException]. |
Roman Elizarov | d528e3e | 2017-01-23 15:40:05 +0300 | [diff] [blame] | 29 | */ |
Roman Elizarov | 1216e91 | 2017-02-22 09:57:06 +0300 | [diff] [blame^] | 30 | suspend fun yield(): Unit = suspendCoroutineOrReturn sc@ { cont -> |
| 31 | val context = cont.context |
| 32 | val job = context[Job] |
| 33 | if (job != null && job.isCompleted) throw job.getCompletionException() |
| 34 | if (cont !is DispatchedContinuation<Unit>) return@sc Unit |
| 35 | if (!cont.dispatcher.isDispatchNeeded(context)) return@sc Unit |
| 36 | cont.dispatchYield(job, Unit) |
| 37 | COROUTINE_SUSPENDED |
Roman Elizarov | d528e3e | 2017-01-23 15:40:05 +0300 | [diff] [blame] | 38 | } |