Actor is deprecated, I know.
Therefor, I doubt the current version will be ported to Kotlin multiplatform and native.
I cannot do it myself either, as it does internal function calls.
How can I use actor in multiplatform?
Or, what’s the alternative?
Those internal function calls look fairly easy to replace with just a call to launch
. Something like this:
import kotlin.coroutines.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
public fun <E> CoroutineScope.myActor(
context: CoroutineContext = EmptyCoroutineContext,
capacity: Int = 0,
onCompletion: CompletionHandler? = null,
block: suspend CoroutineScope.(ReceiveChannel<E>) -> Unit
): SendChannel<E> {
val channel = Channel<E>(capacity)
val job = launch(context) {
try {
block(channel)
} finally {}
}
if (onCompletion != null) job.invokeOnCompletion(handler = onCompletion)
return channel
}
suspend fun main() {
coroutineScope {
val sendChannel = myActor<String> {
for (item in it) { println(item) }
}
sendChannel.send("first")
sendChannel.send("second")
sendChannel.close()
}
}
I ditched the the coroutine start parameter for brevity but if you want to add it, then you can pass that through too, just remember to return a wrapper for the returned SendChannel
that will actually start the coroutine. Should be able to adapt LazyActorCoroutine in the source code into a SendChannel wrapper.
2 Likes