I’m trying to make Zip
two Publishers
with two different functions, but it’s not working as expected. I have a chance to one may failure and one success. but even one is successful I’m not getting a successful response in the sink
. Here is my code, help is greatly appreciated.
struct ContentView: View {
@State var buttonTapped = false
@State var cancellable = Set<AnyCancellable>()
var body: some View {
Group {
Text("Home")
}.onAppear {
Publishers.Zip(fetchData1(), fetchData2())
.sink(receiveCompletion: { first in
switch first {
case .failure(let er):
print(er)
case .finished:
print("ss")
}
}, receiveValue: { (a, b) in
print(a, b)
// Not printing success value
}).store(in: &cancellable)
}
}
func fetchData1() -> Future<Bool, ErrorType> {
return Future { promise in
promise(.failure(.error("fetchData1 failed")))
}
}
func fetchData2() -> Future<String, ErrorType> {
return Future { promise in
promise(.success("fetchData success "))
}
}
}
enum ErrorType: Error {
case error(String)
}
2
Answers
Below is a playground that demonstrates each case.
It includes a function
makeRequest
that creates aFuture
to simulate a request that either succeeds or fails.At the heart of the sample is a pattern:
if the request succeeds, the value we pass to later stages indicates success. If it fails, then
catch
returns a publisher that generates the same kind of thing, but indicating failure.That pattern is used recursively to handle each case in a slightly different way.
Your code is good. Not sure your requirement, but it works this way,
Check out the doc from apple:
Use Publishers.Zip to combine the latest elements from two publishers and emit a tuple to the downstream. The returned publisher waits until both publishers have emitted an event, then delivers the oldest unconsumed event from each publisher together as a tuple to the subscriber.