Skip to content

Commit

Permalink
Add asDisposable convenience property to Task
Browse files Browse the repository at this point in the history
Offers a convenient way to return Tasks as a `Disposable` instead of having to wrap it with `AnonymousDisposable`, for example in an `EffectHandler`
  • Loading branch information
Louis Debaere committed Feb 12, 2024
1 parent c7cee61 commit 6026c24
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
7 changes: 7 additions & 0 deletions MobiusCore/Source/Disposables/Task+Disposable.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public extension Task {

var asDisposable: any Disposable {
AnonymousDisposable { cancel() }
}
}
29 changes: 29 additions & 0 deletions MobiusCore/Test/Task+DisposableTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import MobiusCore
import Nimble
import Quick

@available(iOS 13.0, *)
class TaskDisposableTests: QuickSpec {
override func spec() {
describe("Task+Disposable") {
var task: Task<Void, any Error>!
var disposable: Disposable!

beforeEach {
task = Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
}
disposable = task.asDisposable
}

it("starts off not cancelled") {
expect(task.isCancelled).to(beFalse())
}

it("disposable cancels the task that owns it") {
disposable.dispose()
expect(task.isCancelled).to(beTrue())
}
}
}
}

0 comments on commit 6026c24

Please sign in to comment.