From 09f36200dd631369ecc38a88046d6e472573c45f Mon Sep 17 00:00:00 2001 From: kean Date: Sat, 4 May 2024 15:52:26 -0400 Subject: [PATCH] Use AsyncStream to model ImageTask/events --- Sources/Nuke/ImageTask.swift | 17 ++++++----------- .../ImagePipelineAsyncAwaitTests.swift | 5 ++--- 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/Sources/Nuke/ImageTask.swift b/Sources/Nuke/ImageTask.swift index 578748bca..8c08b7c24 100644 --- a/Sources/Nuke/ImageTask.swift +++ b/Sources/Nuke/ImageTask.swift @@ -115,9 +115,7 @@ public final class ImageTask: Hashable, CustomStringConvertible, @unchecked Send // MARK: - Events /// The events sent by the pipeline during the task execution. - public var events: AnyPublisher { - withState { $0.makeEvents().eraseToAnyPublisher() } - } + public var events: AsyncStream { makeStream { $0 } } /// An event produced during the runetime of the task. public enum Event: Sendable { @@ -266,7 +264,11 @@ extension ImageTask.Event { extension ImageTask { private func makeStream(of closure: @escaping (Event) -> T?) -> AsyncStream { AsyncStream { continuation in - guard let events = _eventIfNotCompleted else { + let events: PassthroughSubject? = withState { + guard $0.taskState == .running else { return nil } + return $0.makeEvents() + } + guard let events else { return continuation.finish() } let cancellable = events.sink { _ in @@ -288,13 +290,6 @@ extension ImageTask { } } - private var _eventIfNotCompleted: PassthroughSubject? { - withState { - guard $0.taskState == .running else { return nil } - return $0.makeEvents() - } - } - private func withState(_ closure: (inout MutableState) -> T) -> T { os_unfair_lock_lock(lock) defer { os_unfair_lock_unlock(lock) } diff --git a/Tests/NukeTests/ImagePipelineTests/ImagePipelineAsyncAwaitTests.swift b/Tests/NukeTests/ImagePipelineTests/ImagePipelineAsyncAwaitTests.swift index 86ad1f00c..a5b012163 100644 --- a/Tests/NukeTests/ImagePipelineTests/ImagePipelineAsyncAwaitTests.swift +++ b/Tests/NukeTests/ImagePipelineTests/ImagePipelineAsyncAwaitTests.swift @@ -385,9 +385,8 @@ class ImagePipelineAsyncAwaitTests: XCTestCase, @unchecked Sendable { // MARK: - ImageTask Integration - // TODO: - Re-enable @available(macOS 12, iOS 15, tvOS 15, watchOS 9, *) - func _testImageTaskEvents() async { + func testImageTaskEvents() async { // GIVEN let dataLoader = MockProgressiveDataLoader() pipeline = pipeline.reconfigured { @@ -397,7 +396,7 @@ class ImagePipelineAsyncAwaitTests: XCTestCase, @unchecked Sendable { // WHEN let task = pipeline.loadImage(with: Test.request) { _ in } - for await event in task.events.values { + for await event in task.events { switch event { case .preview(let response): recordedPreviews.append(response)