Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,8 @@ final class MovieLoader: ObservableObject {
}

func refresh() async {
do {
let page = try await api.getMovies(filter: filter, page: 1)
pages = .success([page])
}
catch {
pages = .failure(error)
pages = await AsyncPhase {
try await [api.getMovies(filter: filter, page: 1)]
}
}

Expand Down
21 changes: 7 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1379,13 +1379,9 @@ class MessageLoader: ObservableObject {
}

func load() async {
do {
let api = context.read(APIClientAtom())
let messages = try await api.fetchMessages(offset: 0)
phase = .success(messages)
}
catch {
phase = .failure(error)
let api = context.read(APIClientAtom())
phase = await AsyncPhase {
try await api.fetchMessages(offset: 0)
}
}

Expand All @@ -1394,14 +1390,11 @@ class MessageLoader: ObservableObject {
return
}

do {
let api = context.read(APIClientAtom())
let next = try await api.fetchMessages(offset: messages.count)
phase = .success(messages + next)
}
catch {
phase = .failure(error)
let api = context.read(APIClientAtom())
let nextPhase = await AsyncPhase {
try await api.fetchMessages(offset: messages.count)
}
phase = nextPhase.map { messages + $0 }
}
}
```
Expand Down
14 changes: 14 additions & 0 deletions Sources/Atoms/AsyncPhase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@ public enum AsyncPhase<Success, Failure: Error> {
}
}

/// Creates a new phase by evaluating a async throwing closure, capturing the
/// returned value as a success, or any thrown error as a failure.
///
/// - Parameter body: A async throwing closure to evaluate.
public init(catching body: () async throws -> Success) async where Failure == Error {
do {
let value = try await body()
self = .success(value)
}
catch {
self = .failure(error)
}
}

/// A boolean value indicating whether `self` is ``AsyncPhase/suspending``.
public var isSuspending: Bool {
guard case .suspending = self else {
Expand Down
8 changes: 8 additions & 0 deletions Tests/AtomsTests/AsyncPhaseTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@ final class AsyncPhaseTests: XCTestCase {
XCTAssertEqual(results.map(AsyncPhase.init), expected)
}

func testAsyncInit() async {
let success = await AsyncPhase { 100 }
let failure = await AsyncPhase { throw URLError(.badURL) }

XCTAssertEqual(success.value, 100)
XCTAssertEqual(failure.error as? URLError, URLError(.badURL))
}

func testMap() {
let phase = AsyncPhase<Int, Error>.success(0)
.map(String.init)
Expand Down