Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# DurianRx releases

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

## [5.0.2] - 2025-01-31
### Fixed
Expand Down
12 changes: 12 additions & 0 deletions src/main/java/com/diffplug/common/rx/GuardedExecutor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,13 @@ import java.util.*
import java.util.concurrent.CompletionStage
import java.util.concurrent.Executor
import java.util.function.Supplier
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch

/**
* GuardedExecutor is an [Executor] and [RxSubscriber] which promises to cancel its subscriptions
Expand All @@ -31,6 +35,14 @@ import kotlinx.coroutines.flow.Flow
* Useful for tying asynchronous tasks to gui elements.
*/
open class GuardedExecutor(val delegate: RxExecutor, val guard: Chit) : Executor, RxSubscriber {
val scope: CoroutineScope by lazy {
CoroutineScope(SupervisorJob() + delegate.dispatcher).apply {
guard.runWhenDisposed { cancel() }
}
}

fun launch(block: suspend CoroutineScope.() -> Unit): Job = scope.launch(block = block)

override fun execute(command: Runnable) {
delegate.executor.execute(guard.guard(command))
}
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/com/diffplug/common/rx/RxExecutor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ import kotlinx.coroutines.launch
class RxExecutor internal constructor(val executor: Executor, val dispatcher: CoroutineDispatcher) :
RxSubscriber {

fun launch(block: suspend CoroutineScope.() -> Unit): Job =
CoroutineScope(Job() + dispatcher).launch(block = block)

interface Has : Executor {
val rxExecutor: RxExecutor
}
Expand Down