Are there any coroutines constructs that would hel...
# coroutines
m
Are there any coroutines constructs that would help me with creation of "global, stoppable, restartable actor"? Basically an actor that is running on global scope (shared logic used between multiple modules), but it can be stopped and restarted as needed. Something like this:
Copy code
private var actorChannel = Channel(Capacity.UNLIMITED)
private var actorJob : Job? = null

fun performSomeOtherCommand() {
    if (actorJob?.isActive != true) {
        restartActor()
    }

    actor.offer(...)
}

suspend fun stopActor() {
    actor.offer(StopCommand)

    actorJob?.join()
}

private fun restartActor() {
    actorJob = GlobalScope.launch {
        actorChannel.consumeEach {
            ...

            if (it == StopCommand) {
                return@launch
            }
        }
    }
}
But the problem with above example is that it is not thread safe. One thread could call
performSomeOtherCommand()
while the actor is still being stopped by
stopActor()
. Easiest solution would be to just not stop the actor and let it live forever, but since it's in
GlobalScope
, it would never be garbage collected when not needed. I could use mutexes and synchronized blocks but I feel that this kinda ruins the point of having an actor.
u
An actor itself should be really light weight. Gc could become relevant if the actor holds lots of state. In that case I'd suggest to keep it running and only tell it to free it's resources
b
Why do you need to stop and restart the actor? Would it be enough to pause/resume?
m
I basically want to remove it from memory when not needed, but @uli might have a point here - actor itself does not really use that much memory.
b
I would probably take some inspiration here: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/actor.html I know it’s obsolete and will be removed in respect of a more complex actor. But it’s still worth checking out.
m
Yes that is what I would use normally (when there is no requirement to stop the actor)