From fec8c033136def49b30e6ca1c827079a32b7c471 Mon Sep 17 00:00:00 2001 From: Michael Bull Date: Sun, 10 Mar 2024 23:09:09 +0000 Subject: [PATCH] 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/ --- .../result/coroutines/binding/SuspendableBinding.kt | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/kotlin-result-coroutines/src/commonMain/kotlin/com/github/michaelbull/result/coroutines/binding/SuspendableBinding.kt b/kotlin-result-coroutines/src/commonMain/kotlin/com/github/michaelbull/result/coroutines/binding/SuspendableBinding.kt index f071ee9..88c0a9e 100644 --- a/kotlin-result-coroutines/src/commonMain/kotlin/com/github/michaelbull/result/coroutines/binding/SuspendableBinding.kt +++ b/kotlin-result-coroutines/src/commonMain/kotlin/com/github/michaelbull/result/coroutines/binding/SuspendableBinding.kt @@ -29,8 +29,11 @@ public suspend inline fun 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 @@ -45,8 +48,8 @@ public interface SuspendableResultBinding : CoroutineScope { @PublishedApi internal class SuspendableResultBindingImpl( - override val coroutineContext: CoroutineContext, -) : SuspendableResultBinding { + delegate: CoroutineScope, +) : SuspendableResultBinding, CoroutineScope by delegate { private val mutex = Mutex() lateinit var result: Err @@ -57,7 +60,7 @@ internal class SuspendableResultBindingImpl( is Err -> mutex.withLock { if (::result.isInitialized.not()) { result = this - this@SuspendableResultBindingImpl.cancel(BindCancellationException) + coroutineContext.cancel(BindCancellationException) } throw BindCancellationException