Skip to content

Commit

Permalink
Docs.
Browse files Browse the repository at this point in the history
  • Loading branch information
colinrtwhite committed Dec 22, 2024
1 parent e9f849c commit 0e684c3
Showing 1 changed file with 22 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.withContext

/**
* A [CoroutineScope] with a special [CoroutineContext] that enables [ForwardingUnconfinedCoroutineDispatcher]
* to enable dispatching after it is replaced in the context.
*/
internal fun ForwardingUnconfinedCoroutineScope(
context: CoroutineContext,
) = CoroutineScope(
Expand All @@ -22,6 +26,24 @@ internal fun ForwardingUnconfinedCoroutineScope(
}
)

/**
* Calls [block] with a [ForwardingUnconfinedCoroutineDispatcher] replacing the current dispatcher.
*/
internal suspend inline fun <T> withForwardingUnconfinedCoroutineDispatcher(
originalDispatcher: CoroutineDispatcher,
crossinline block: suspend CoroutineScope.() -> T
): T {
val unconfinedDispatcher = ForwardingUnconfinedCoroutineDispatcher(originalDispatcher)
return withContext(unconfinedDispatcher) {
try {
block()
} finally {
// Optimization to avoid dispatching when there's nothing left to do.
unconfinedDispatcher.unconfined = true
}
}
}

/**
* A [CoroutineDispatcher] that delegates to [Dispatchers.Unconfined] while [unconfined] is true
* and [delegate] when [unconfined] is false.
Expand Down Expand Up @@ -56,18 +78,3 @@ internal class ForwardingUnconfinedCoroutineDispatcher(
return "ForwardingUnconfinedCoroutineDispatcher(delegate=$delegate)"
}
}

internal suspend inline fun <T> withForwardingUnconfinedCoroutineDispatcher(
originalDispatcher: CoroutineDispatcher,
crossinline block: suspend CoroutineScope.() -> T
): T {
val unconfinedDispatcher = ForwardingUnconfinedCoroutineDispatcher(originalDispatcher)
return withContext(unconfinedDispatcher) {
try {
block()
} finally {
// Optimization to avoid dispatching when there's nothing left to do.
unconfinedDispatcher.unconfined = true
}
}
}

0 comments on commit 0e684c3

Please sign in to comment.