Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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