Created
March 10, 2023 11:27
-
-
Save Andrew0000/e3eb7c3166c6c4939f3cdea2611030ba to your computer and use it in GitHub Desktop.
LockedObj
This file contains hidden or 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.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