Skip to content

Commit 6026c24

Browse files
author
Louis Debaere
committed
Add asDisposable convenience property to Task
Offers a convenient way to return Tasks as a `Disposable` instead of having to wrap it with `AnonymousDisposable`, for example in an `EffectHandler`
1 parent c7cee61 commit 6026c24

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
2+
public extension Task {
3+
4+
var asDisposable: any Disposable {
5+
AnonymousDisposable { cancel() }
6+
}
7+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import MobiusCore
2+
import Nimble
3+
import Quick
4+
5+
@available(iOS 13.0, *)
6+
class TaskDisposableTests: QuickSpec {
7+
override func spec() {
8+
describe("Task+Disposable") {
9+
var task: Task<Void, any Error>!
10+
var disposable: Disposable!
11+
12+
beforeEach {
13+
task = Task {
14+
try? await Task.sleep(nanoseconds: 1_000_000_000)
15+
}
16+
disposable = task.asDisposable
17+
}
18+
19+
it("starts off not cancelled") {
20+
expect(task.isCancelled).to(beFalse())
21+
}
22+
23+
it("disposable cancels the task that owns it") {
24+
disposable.dispose()
25+
expect(task.isCancelled).to(beTrue())
26+
}
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)