T
05/01/2021, 12:09 PMval loginSequence = SharedMethod<String>()
suspend fun request() {
try {
loginSequence
.awaitIfNeeded()
return doRequest(...)
} catch(e: LoginRequiredException) {
return loginSequence.awaitOrBlock(
onBlockReturn = {
return@awaitOrBlock executeLoginSequence(e)
},
onAwaitReturn = {
return@awaitOrBlock doRequest(
...
)
})
}
}
with the implementation of this class with mutexes:
class SharedMethod<T> {
private val mutex: Mutex = Mutex()
suspend fun awaitOrBlock(
onBlockReturn: suspend () -> T,
onAwaitReturn: suspend () -> T
): T = coroutineScope {
val isLocked = mutex.tryLock()
if (!isLocked) {
awaitIfNeeded()
return@coroutineScope onAwaitReturn()
}
try {
return@coroutineScope onBlockReturn()
} finally {
mutex.unlock()
}
}
suspend fun awaitIfNeeded() {
while (mutex.isLocked) {
delay(1000)
}
}
}
Is there a better way to implement this behaviour? Especially the "while (mutex.isLocked) {...}" seems pretty ugly.
Is this the right place for using mutexes? Happy to hear your thoughts. :)Dominaezzz
05/01/2021, 12:20 PMlock
the mutex isn't of trying to poll it.T
05/03/2021, 5:56 PM