Matej Drobnič
01/10/2020, 6:11 AMprivate 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.uli
01/10/2020, 7:05 AMbob
01/10/2020, 8:30 AMMatej Drobnič
01/10/2020, 8:33 AMbob
01/10/2020, 8:34 AMMatej Drobnič
01/10/2020, 9:05 AM