Skip to content

Commit 47eaa7b

Browse files
mluisbrownmbrandonw
andcommitted
Add Effect.task for wrapping units of async/await work (#715)
* wip * wip * wip * wip * wip * wip * wip * wip * wip * docs * clean up * Remove bad test Co-authored-by: Brandon Williams <[email protected]>
1 parent 6ecefdb commit 47eaa7b

File tree

3 files changed

+335
-144
lines changed

3 files changed

+335
-144
lines changed

Examples/CaseStudies/SwiftUICaseStudies/FactClient.swift

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,41 @@ struct FactClient {
99
struct Error: Swift.Error, Equatable {}
1010
}
1111

12-
extension FactClient {
1312
// This is the "live" fact dependency that reaches into the outside world to fetch trivia.
1413
// Typically this live implementation of the dependency would live in its own module so that the
1514
// main feature doesn't need to compile it.
15+
extension FactClient {
16+
#if compiler(>=5.5)
1617
static let live = Self(
1718
fetch: { number in
18-
URLSession.shared.reactive.data(
19-
with: URLRequest(url: URL(string: "http://numbersapi.com/\(number)/trivia")!)
20-
)
21-
.map { data, _ in String(decoding: data, as: UTF8.self) }
22-
.flatMapError { _ in
23-
Effect(value: "\(number) is a good number Brent")
24-
.delay(1, on: QueueScheduler.main)
19+
Effect.task {
20+
do {
21+
let (data, _) = try await URLSession.shared
22+
.data(from: URL(string: "http://numbersapi.com/\(number)/trivia")!)
23+
return String(decoding: data, as: UTF8.self)
24+
} catch {
25+
await Task.sleep(NSEC_PER_SEC)
26+
return "\(number) is a good number Brent"
27+
}
28+
}
29+
.setFailureType(to: Error.self)
30+
.eraseToEffect()
2531
}
26-
.promoteError(Error.self)
27-
})
32+
)
33+
#else
34+
static let live = Self(
35+
fetch: { number in
36+
URLSession.shared.reactive.data(
37+
with: URLRequest(url: URL(string: "http://numbersapi.com/\(number)/trivia")!)
38+
)
39+
.map { data, _ in String(decoding: data, as: UTF8.self) }
40+
.flatMapError { _ in
41+
Effect(value: "\(number) is a good number Brent")
42+
.delay(1, on: QueueScheduler.main)
43+
}
44+
.promoteError(Error.self)
45+
})
46+
#endif
2847
}
2948

3049
#if DEBUG

0 commit comments

Comments
 (0)