diff --git a/MobiusCore/Source/Disposables/Task+Disposable.swift b/MobiusCore/Source/Disposables/Task+Disposable.swift new file mode 100644 index 00000000..0d6608e2 --- /dev/null +++ b/MobiusCore/Source/Disposables/Task+Disposable.swift @@ -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() } + } +} diff --git a/MobiusCore/Test/Task+DisposableTests.swift b/MobiusCore/Test/Task+DisposableTests.swift new file mode 100644 index 00000000..73e7e071 --- /dev/null +++ b/MobiusCore/Test/Task+DisposableTests.swift @@ -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! + 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()) + } + } + } +}