带有不同错误的`flatMap`发布者

时间:2020-08-07 18:23:48

标签: ios swift networking functional-programming combine

我有一个像下面这样的Swift发布者

let item = PassthrogutSubject<String, Never>()

收到我要发出网络请求的字符串

为此,我正在使用flatMap

我的网络请求签名如下:

func loadDetails(_ code: String) -> AnyPublisher<CustomType, ErrorAlert>

如何执行以下操作:

$item
 .filter { !$0.isEmpty }
 .flatMap { [unowned self] (string) in
    self.viewModel.loadDetails(string) }
 .receive(on: DispatchQueue.main)
 .sink(receiveCompletion: { _ in
     ...
  }) {  ... }
 .store(in: &subscriptions)

错误:

Instance method 'flatMap(maxPublishers:_:)' requires the types 'Published<Value>.Publisher.Failure' (aka 'Never') and 'Alert' be equivalent

1 个答案:

答案 0 :(得分:2)

半路我的问题是在接收第一个订户时与以下运算符一起解决了

$item
 .filter { !$0.isEmpty }
 .setFailureType(to: ErrorAlert.self) // <---- ? HERE
 .flatMap { [unowned self] (string) in
    self.viewModel.loadDetails(string) }
 .receive(on: DispatchQueue.main)
 .sink(receiveCompletion: { _ in
     ...
  }) {  ... }
 .store(in: &subscriptions)