Skip to content

Commit

Permalink
Use delegation for SuspendableResultBindingImpl
Browse files Browse the repository at this point in the history
The Kotlin docs for CoroutineScope[1] explicitly state that:

"Manual implementation of this interface is not recommended,
implementation by delegation should be preferred instead."

[1] https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/
  • Loading branch information
michaelbull committed Mar 10, 2024
1 parent 716109a commit 0f21774
Showing 1 changed file with 8 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ public suspend inline fun <V, E> binding(crossinline block: suspend SuspendableR

return try {
coroutineScope {
receiver = SuspendableResultBindingImpl(this.coroutineContext)
with(receiver) { Ok(block()) }
receiver = SuspendableResultBindingImpl(this)

with(receiver) {
Ok(block())
}
}
} catch (ex: BindCancellationException) {
receiver.result
Expand All @@ -45,8 +48,8 @@ public interface SuspendableResultBinding<E> : CoroutineScope {

@PublishedApi
internal class SuspendableResultBindingImpl<E>(
override val coroutineContext: CoroutineContext,
) : SuspendableResultBinding<E> {
delegate: CoroutineScope,
) : SuspendableResultBinding<E>, CoroutineScope by delegate {

private val mutex = Mutex()
lateinit var result: Err<E>
Expand All @@ -57,7 +60,7 @@ internal class SuspendableResultBindingImpl<E>(
is Err -> mutex.withLock {
if (::result.isInitialized.not()) {
result = this
this@SuspendableResultBindingImpl.cancel(BindCancellationException)
coroutineContext.cancel(BindCancellationException)
}

throw BindCancellationException
Expand Down

0 comments on commit 0f21774

Please sign in to comment.