Skip to content

Commit a772559

Browse files
authored
Add suspend fun support (#13)
2 parents ea78567 + 464c522 commit a772559

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

CHANGES.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
# DurianRx releases
22

33
## [Unreleased]
4+
### Added
5+
- `RxExecutor.launch` lets a user run `suspend` functions within that executor.
6+
- `GuardedExecutor` now has a lazily populated scope which cancels when its guard disposes, as well as a `launch` method.
47

58
## [5.0.2] - 2025-01-31
69
### Fixed

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
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ import kotlinx.coroutines.launch
3636
class RxExecutor internal constructor(val executor: Executor, val dispatcher: CoroutineDispatcher) :
3737
RxSubscriber {
3838

39+
fun launch(block: suspend CoroutineScope.() -> Unit): Job =
40+
CoroutineScope(Job() + dispatcher).launch(block = block)
41+
3942
interface Has : Executor {
4043
val rxExecutor: RxExecutor
4144
}

0 commit comments

Comments
 (0)