forked from kscience/kmath
safe scopes
This commit is contained in:
parent
6384182593
commit
7744880ce7
@ -9,7 +9,7 @@ private typealias Disposable = () -> Unit
|
|||||||
|
|
||||||
public class NoaScope {
|
public class NoaScope {
|
||||||
|
|
||||||
private val disposables: ArrayDeque<Disposable> = ArrayDeque(0)
|
internal val disposables: ArrayDeque<Disposable> = ArrayDeque(0)
|
||||||
|
|
||||||
public fun disposeAll() {
|
public fun disposeAll() {
|
||||||
disposables.forEach(Disposable::invoke)
|
disposables.forEach(Disposable::invoke)
|
||||||
@ -20,15 +20,30 @@ public class NoaScope {
|
|||||||
disposables += {
|
disposables += {
|
||||||
try {
|
try {
|
||||||
disposable()
|
disposable()
|
||||||
} catch (ignored: Throwable) {
|
} catch (e: Throwable) {
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal inline fun <R> withNoaScope(block: NoaScope.() -> R): R {
|
internal fun addAll(scope: NoaScope) {
|
||||||
|
disposables.addAll(scope.disposables)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun <R> withNoaScope(block: NoaScope.() -> R): R? {
|
||||||
val noaScope = NoaScope()
|
val noaScope = NoaScope()
|
||||||
val result = noaScope.block()
|
val result = try { noaScope.block() } catch (e: Throwable) { null }
|
||||||
noaScope.disposeAll()
|
noaScope.disposeAll()
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun <R> withNoaScope(scope: NoaScope, block: NoaScope.() -> R): R? {
|
||||||
|
val noaScope = NoaScope()
|
||||||
|
val result = try { noaScope.block() } catch (e: Throwable) { null }
|
||||||
|
if (result == null){
|
||||||
|
noaScope.disposeAll()
|
||||||
|
} else {
|
||||||
|
scope.addAll(noaScope)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user