Updated on 2026-08-14

This commit is contained in:
Tangem 2024-08-29 18:25:34 +04:00
parent 64a40de825
commit 4a25e38ccc
12 changed files with 151 additions and 28 deletions

View file

@ -46,14 +46,36 @@ abstract class Model : InstanceKeeper.Instance {
progressFlow: MutableSharedFlow<Boolean>,
dispatcher: CoroutineDispatcher = dispatchers.mainImmediate,
crossinline block: suspend () -> Unit,
): Job = resource(
acquire = { progressFlow.emit(true) },
release = { progressFlow.emit(false) },
dispatcher = dispatcher,
block = block,
)
/**
* Launches [block] in the model's scope and acquires a resource before executing the block and releases it after.
*
* @param acquire The block of code to acquire the resource.
* @param release The block of code to release the resource.
* @param dispatcher The [CoroutineDispatcher] to launch the coroutine. Default is [Dispatchers.Main.immediate].
* @param block The block of code to execute.
*
* @return The [Job] of the launched coroutine.
* */
protected inline fun resource(
crossinline acquire: suspend () -> Unit,
crossinline release: suspend () -> Unit,
dispatcher: CoroutineDispatcher = dispatchers.mainImmediate,
crossinline block: suspend () -> Unit,
): Job = modelScope.launch(dispatcher) {
progressFlow.emit(value = true)
acquire()
try {
block()
} finally {
withContext(NonCancellable) {
progressFlow.emit(value = false)
release()
}
}
}

View file

@ -44,11 +44,24 @@ inline fun <T> MutableList<T>.replaceBy(item: T, predicate: (T) -> Boolean): Boo
*/
inline fun <T> List<T>.addOrReplace(item: T, predicate: (T) -> Boolean): List<T> {
val mutableList = this.toMutableList()
val isReplaced = mutableList.replaceBy(item, predicate)
if (!isReplaced) {
mutableList.add(item)
}
mutableList.addOrReplace(item, predicate)
return mutableList
}
/**
* Adds the specified element to the mutable list or replaces an existing element.
*
* !!!This function is not thread-safe!!!
*
* @param item The element to be added or replace the existing one.
* @param predicate The condition to replace an existing element.
*/
inline fun <T> MutableList<T>.addOrReplace(item: T, predicate: (T) -> Boolean) {
val isReplaced = replaceBy(item, predicate)
if (!isReplaced) {
add(item)
}
}