Skip to content

Instantly share code, notes, and snippets.

@vemilyus
Created December 30, 2018 14:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vemilyus/c19f5d75525a37b33c4640bfd61158fe to your computer and use it in GitHub Desktop.
Save vemilyus/c19f5d75525a37b33c4640bfd61158fe to your computer and use it in GitHub Desktop.
Sample implementation of ActorState with read-write separation
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