Skip to content

Commit

Permalink
Use AsyncStream to model ImageTask/events
Browse files Browse the repository at this point in the history
  • Loading branch information
kean committed May 4, 2024
1 parent 60d06ba commit 09f3620
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 14 deletions.
17 changes: 6 additions & 11 deletions Sources/Nuke/ImageTask.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Event, Never> {
withState { $0.makeEvents().eraseToAnyPublisher() }
}
public var events: AsyncStream<Event> { makeStream { $0 } }

/// An event produced during the runetime of the task.
public enum Event: Sendable {
Expand Down Expand Up @@ -266,7 +264,11 @@ extension ImageTask.Event {
extension ImageTask {
private func makeStream<T>(of closure: @escaping (Event) -> T?) -> AsyncStream<T> {
AsyncStream { continuation in
guard let events = _eventIfNotCompleted else {
let events: PassthroughSubject<Event, Never>? = withState {
guard $0.taskState == .running else { return nil }
return $0.makeEvents()
}
guard let events else {
return continuation.finish()
}
let cancellable = events.sink { _ in
Expand All @@ -288,13 +290,6 @@ extension ImageTask {
}
}

private var _eventIfNotCompleted: PassthroughSubject<Event, Never>? {
withState {
guard $0.taskState == .running else { return nil }
return $0.makeEvents()
}
}

private func withState<T>(_ closure: (inout MutableState) -> T) -> T {
os_unfair_lock_lock(lock)
defer { os_unfair_lock_unlock(lock) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
Expand Down

0 comments on commit 09f3620

Please sign in to comment.