commonMain.com.badoo.reaktive.utils.lock.ConditionLockExt.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of utils-internal-jvm Show documentation
Show all versions of utils-internal-jvm Show documentation
Kotlin multi-platform implementation of Reactive Extensions
package com.badoo.reaktive.utils.lock
import com.badoo.reaktive.utils.InternalReaktiveApi
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
@OptIn(ExperimentalContracts::class)
@InternalReaktiveApi
inline fun ConditionLock.synchronized(block: () -> T): T {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
lock()
try {
return block()
} finally {
unlock()
}
}
@InternalReaktiveApi
inline fun ConditionLock.waitFor(timeout: Duration, predicate: () -> Boolean): Boolean {
require(!timeout.isNegative()) { "Timeout must not be negative" }
var remainingTimeout = timeout
while (true) {
if (predicate()) {
return true
}
if (!remainingTimeout.isPositive()) {
return false
}
remainingTimeout = await(timeout = timeout)
}
}
@InternalReaktiveApi
fun ConditionLock.waitForOrFail(timeout: Duration = 5.seconds, predicate: () -> Boolean) {
if (!waitFor(timeout, predicate)) {
error("Timeout waiting for condition")
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy