Created
December 14, 2021 14:20
-
-
Save handstandsam/0ac44478f5378c079904458b0a013f83 to your computer and use it in GitHub Desktop.
There is no support for Actor in Kotlin Multiplatform, nor is it planned. More info: https://github.com/Kotlin/kotlinx.coroutines/issues/87). What are the flaws of this?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* JVM Implementation from KotlinX Coroutines | |
* https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/jvm/src/channels/Actor.kt#L31-L124 | |
*/ | |
@ObsoleteCoroutinesApi | |
public fun <E> CoroutineScope.actor( | |
context: CoroutineContext = EmptyCoroutineContext, | |
capacity: Int = 0, // todo: Maybe Channel.DEFAULT here? | |
start: CoroutineStart = CoroutineStart.DEFAULT, | |
onCompletion: CompletionHandler? = null, | |
block: suspend ActorScope<E>.() -> Unit | |
): SendChannel<E> { | |
val newContext = newCoroutineContext(context) | |
val channel = Channel<E>(capacity) | |
val coroutine = if (start.isLazy) | |
LazyActorCoroutine(newContext, channel, block) else | |
ActorCoroutine(newContext, channel, active = true) | |
if (onCompletion != null) coroutine.invokeOnCompletion(handler = onCompletion) | |
coroutine.start(start, coroutine, block) | |
return coroutine | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Suggested in: https://discuss.kotlinlang.org/t/actor-kotlin-common/19569 | |
*/ | |
@OptIn(ExperimentalCoroutinesApi::class) | |
public fun <E> CoroutineScope.multiplatformActor( | |
context: CoroutineContext = EmptyCoroutineContext, | |
capacity: Int = 0, | |
onCompletion: CompletionHandler? = null, | |
block: suspend CoroutineScope.(ReceiveChannel<E>) -> Unit | |
): SendChannel<E> { | |
val newContext = newCoroutineContext(context) | |
val channel = Channel<E>(capacity) | |
val job = launch(newContext) { | |
try { | |
block(channel) | |
} finally { | |
} | |
} | |
if (onCompletion != null) job.invokeOnCompletion(handler = onCompletion) | |
return this | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment