RxSwift链接:用Rxswift编写此代码的更好方法是什么?

时间:2019-02-18 23:47:57

标签: swift rx-swift

我是RxSwift的新手。很新通常,要在没有Rx的情况下链接您,可以将下一个函数放入补全闭包中。同行们告诉我改用flatmap或我们的concatmap版本,但从未给我提供示例。任何人都可以使用flatmap或concatmap的快速版本转换此代码吗?我还是新手,请谨慎对待判断。

 SVProgressHUD.show()
    params.address = address
    print(params)
    viewmodel
      .postSeekerAvatar(image: image).subscribe(onSuccess: {
//        SVProgressHUD.dismiss()
//        SVProgressHUD.show()
        self.viewmodel
          .updateSeeker(withFirstName: params.firstName, lastName: params.lastName, isBusiness: params.isBusiness, abn: "none", address: params.address)
          .subscribe(onSuccess: {
            SVProgressHUD.dismiss()

        self.performSegue(withIdentifier: SegueConstants.toProfileForm, sender: self)

      }) { (error) in
        SVProgressHUD.showDismissableError(with: error.message)
      }.disposed(by: self.disposeBag)
  }) { (error) in
    SVProgressHUD.showDismissableInfo(with: error.message)
  }.disposed(by: disposeBag)

2 个答案:

答案 0 :(得分:1)

postSeekerAvatar() method should return a Single response 
Add showLoader/hideLoader method in BaseViewController. 

viewmodel
    .postSeekerAvatar(image: image) //Return Single<Response>
    .do(onSubscribed: presenter.showLoader)
    .do(onDispose: presenter.hideLoader)
    .asCompletable()
    .andThen(update(params: params))
    .subscribe()
    .disposeOnDeactivate(interactor: self)

//Returns a completable 
  private func update(params: Model) -> Completable {
    viewmodel
      .updateSeeker(
        withFirstName: params.firstName,
        lastName: params.lastName,
        isBusiness: params.isBusiness,
        abn: "none",
        address: params.address
    )
    return Completable.empty()
  }

答案 1 :(得分:1)

因此,您想要的永远不会嵌套subscribe调用。取而代之的是,您将源可观察的值转换为其他可观察的值,有时将其转换为另一个值。

SVProgressHUD.show()
params.address = address
print(params)
viewmodel
  .postSeekerAvatar(image: image)
  .flatMap {
    self.viewmodel
      .updateSeeker(withFirstName: params.firstName, lastName: params.lastName, isBusiness: params.isBusiness, abn: "none", address: params.address)
  }
  .subscribe(onSuccess: {
    SVProgressHUD.dismiss()
      self.performSegue(withIdentifier: SegueConstants.toProfileForm, sender: self)
   }, onError: { (error) in
      SVProgressHUD.showDismissableError(with: error.message)
   })
  .disposed(by: disposeBag)

因此,在这里,第一个postSeekerAvatar将被订阅,并且每次推出一个值时,updateSeeker也将被订阅。如果它们中的任何一个出错,错误关闭将运行。