Skip to content

Commit 7c5f0ef

Browse files
committed
GuardedExecutor now has a lazily populated scope which cancels when its guard disposes, as well as a launch method.
1 parent 1ae4006 commit 7c5f0ef

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

src/main/java/com/diffplug/common/rx/GuardedExecutor.kt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,13 @@ import java.util.*
2020
import java.util.concurrent.CompletionStage
2121
import java.util.concurrent.Executor
2222
import java.util.function.Supplier
23+
import kotlinx.coroutines.CoroutineScope
2324
import kotlinx.coroutines.Deferred
2425
import kotlinx.coroutines.Job
26+
import kotlinx.coroutines.SupervisorJob
27+
import kotlinx.coroutines.cancel
2528
import kotlinx.coroutines.flow.Flow
29+
import kotlinx.coroutines.launch
2630

2731
/**
2832
* GuardedExecutor is an [Executor] and [RxSubscriber] which promises to cancel its subscriptions
@@ -31,6 +35,14 @@ import kotlinx.coroutines.flow.Flow
3135
* Useful for tying asynchronous tasks to gui elements.
3236
*/
3337
open class GuardedExecutor(val delegate: RxExecutor, val guard: Chit) : Executor, RxSubscriber {
38+
val scope: CoroutineScope by lazy {
39+
CoroutineScope(SupervisorJob() + delegate.dispatcher).apply {
40+
guard.runWhenDisposed { cancel() }
41+
}
42+
}
43+
44+
fun launch(block: suspend CoroutineScope.() -> Unit): Job = scope.launch(block = block)
45+
3446
override fun execute(command: Runnable) {
3547
delegate.executor.execute(guard.guard(command))
3648
}

0 commit comments

Comments
 (0)