nuhkoca
11/12/2024, 8:38 PMprivate suspend fun refreshAccounts() {
if (!mutex.isLocked) {
mutex.withLock {
try {
action()
} catch (e: IllegalStateException) {
Timber.e(e)
}
}
}
}
How can I unit test this behavior?
I did this
launch { repository.subscribeToAccounts().test {expectMostRecentItem() } }
launch { repository.subscribeToAccounts().test {expectMostRecentItem() } }
launch { repository.subscribeToAccounts().test {expectMostRecentItem() } }
verify(accountsApi, times(1)).getAccounts()
but accountsApi
is called 3 times not 1PHondogo
11/12/2024, 8:47 PMif (!mutex.isLocked) {mutex.withLock{ ...
To
if (mutex.tryLock()) {
try{...} finally{mutex.unlock()}
}
PHondogo
11/12/2024, 8:51 PMPHondogo
11/12/2024, 8:52 PMnuhkoca
11/12/2024, 8:52 PMnuhkoca
11/12/2024, 8:53 PMaction()
is called once not couple of times when accessed from different coroutines at a timePHondogo
11/12/2024, 8:56 PMnuhkoca
11/12/2024, 8:59 PMwithMutex
block? Is it in coroutines-test
artifact?PHondogo
11/12/2024, 9:09 PMnuhkoca
11/12/2024, 9:11 PMPHondogo
11/12/2024, 9:14 PMmutex.withLock {
if (!someVariableWithActionExecutedFlag) { // declare this variable in the same scope as mutex
action()
someVariableWithActionExecutedFlag = true
}
}
nuhkoca
11/12/2024, 9:14 PMPHondogo
11/12/2024, 9:14 PMnuhkoca
11/12/2024, 9:16 PMPHondogo
11/12/2024, 9:17 PMPHondogo
11/12/2024, 9:18 PMnuhkoca
11/12/2024, 9:22 PMmutex.unlock
should be deleted then right?PHondogo
11/12/2024, 9:23 PMnuhkoca
11/12/2024, 9:26 PMnuhkoca
11/12/2024, 9:34 PMtry catch
inside withLock
because mutex may throw exception if it is locked and tried to be accessed with another coroutines?PHondogo
11/12/2024, 9:50 PMpublic suspend inline fun <T> Mutex.withLock(owner: Any? = null, action: () -> T): T {
lock(owner)
return try {
action()
} finally {
unlock(owner)
}
}
unlock is in finally block, so it will be unlocked in any scenario.
But you have to think how you will handle it for your action. Should you mark action as executed in this case or throw exception for every coroutines, or retry action ...