Created
December 30, 2018 14:48
-
-
Save vemilyus/c19f5d75525a37b33c4640bfd61158fe to your computer and use it in GitHub Desktop.
Sample implementation of ActorState with read-write separation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.CoroutineScope | |
import kotlinx.coroutines.Job | |
import kotlinx.coroutines.ObsoleteCoroutinesApi | |
import kotlinx.coroutines.channels.actor | |
import kotlinx.coroutines.isActive | |
import kotlinx.coroutines.sync.Mutex | |
import kotlinx.coroutines.sync.withLock | |
import kotlin.coroutines.CoroutineContext | |
interface ActorState<T : Any> : CoroutineScope { | |
suspend fun update(block: T.() -> Unit) | |
suspend fun <R> read(block: T.() -> R): R | |
} | |
fun <T : Any> CoroutineScope.actorState(initialState: T): ActorState<T> = | |
ActorStateImpl(initialState, coroutineContext) | |
private class ActorStateImpl<T : Any>( | |
private val state: T, | |
parentContext: CoroutineContext | |
) : ActorState<T> { | |
override val coroutineContext: CoroutineContext = parentContext + Job() | |
private val updatesMutex = Mutex(false) | |
@ObsoleteCoroutinesApi | |
private val updatesChannel = actor<T.() -> Unit> { | |
while (isActive) { | |
while (isActive && updatesMutex.tryLock()) { | |
try { | |
receiveOrNull()?.let { | |
state.it() | |
} | |
} finally { | |
updatesMutex.unlock() | |
} | |
} | |
while (isActive && !updatesMutex.tryLock()) { | |
updatesMutex.unlock() | |
} | |
} | |
} | |
@ObsoleteCoroutinesApi | |
override suspend fun update(block: T.() -> Unit) = | |
updatesChannel.send(block) | |
override suspend fun <R> read(block: T.() -> R) = | |
updatesMutex.withLock { | |
state.block() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment