Use delegation for SuspendableResultBindingImpl

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/
This commit is contained in:
Michael Bull 2024-03-10 23:09:09 +00:00
parent 8d6b0a9eb3
commit fec8c03313

View File

@ -29,8 +29,11 @@ public suspend inline fun <V, E> binding(crossinline block: suspend SuspendableR
return try { return try {
coroutineScope { coroutineScope {
receiver = SuspendableResultBindingImpl(this.coroutineContext) receiver = SuspendableResultBindingImpl(this)
with(receiver) { Ok(block()) }
with(receiver) {
Ok(block())
}
} }
} catch (ex: BindCancellationException) { } catch (ex: BindCancellationException) {
receiver.result receiver.result
@ -45,8 +48,8 @@ public interface SuspendableResultBinding<E> : CoroutineScope {
@PublishedApi @PublishedApi
internal class SuspendableResultBindingImpl<E>( internal class SuspendableResultBindingImpl<E>(
override val coroutineContext: CoroutineContext, delegate: CoroutineScope,
) : SuspendableResultBinding<E> { ) : SuspendableResultBinding<E>, CoroutineScope by delegate {
private val mutex = Mutex() private val mutex = Mutex()
lateinit var result: Err<E> lateinit var result: Err<E>
@ -57,7 +60,7 @@ internal class SuspendableResultBindingImpl<E>(
is Err -> mutex.withLock { is Err -> mutex.withLock {
if (::result.isInitialized.not()) { if (::result.isInitialized.not()) {
result = this result = this
this@SuspendableResultBindingImpl.cancel(BindCancellationException) coroutineContext.cancel(BindCancellationException)
} }
throw BindCancellationException throw BindCancellationException