Skip to content

Instantly share code, notes, and snippets.

@handstandsam
Created December 14, 2021 14:20
Show Gist options
  • Save handstandsam/0ac44478f5378c079904458b0a013f83 to your computer and use it in GitHub Desktop.
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?
/**
* 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
}
/**
* 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