假设存在这样一个结构体:
struct CustomData {
let data1: Int
let data2: String
}
这里有两个方法:
func getInt() -> AnyPublisher<Int, Error> {
return Just(Int.random(in: 0...100))
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
func getString() -> AnyPublisher<String, Error> {
return Just("(Int.random(in: 200...400))")
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
是否有可能使用组合来获得这些函数的输出并在调用链中创建类型为CustomData
的对象?
您可能想要查看各种combine
和merge
调用。例如,使用combineLatest
:
struct ContentView: View {
@State var result: CustomData?
@State var cancellable: AnyCancellable?
var body: some View {
VStack {
if let result {
Text("result: (result.data1) (result.data2)")
}
}
.onAppear {
cancellable =
getInt()
.combineLatest(getString())
.tryMap {
CustomData(data1: $0, data2: $1)
}
.sink(receiveCompletion: { err in
//
}, receiveValue: { customData in
self.result = customData
})
}
}
struct CustomData {
let data1: Int
let data2: String
}
func getInt() -> AnyPublisher<Int, Error> {
return Just(Int.random(in: 0...100))
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
func getString() -> AnyPublisher<String, Error> {
return Just("(Int.random(in: 200...400))")
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
}