Skip to content

Instantly share code, notes, and snippets.

@Andrew0000
Created March 10, 2023 11:27
Show Gist options
  • Select an option

  • Save Andrew0000/e3eb7c3166c6c4939f3cdea2611030ba to your computer and use it in GitHub Desktop.

Select an option

Save Andrew0000/e3eb7c3166c6c4939f3cdea2611030ba to your computer and use it in GitHub Desktop.
LockedObj
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
class LockedObj<T>(
/**
* Use it directly only in [withLock]
*/
var value: T,
) {
private val lock = Mutex()
suspend fun set(newValue: T) {
lock.withLock {
value = newValue
}
}
suspend fun get(): T =
lock.withLock {
value
}
suspend fun update(action: (T) -> T) {
lock.withLock {
value = action(value)
}
}
suspend fun withLock(action: LockedObj<T>.() -> Unit) {
lock.withLock {
action()
}
}
suspend fun withNonCancellableLock(action: LockedObj<T>.() -> Unit) {
withContext(NonCancellable) {
lock.withLock {
action()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment