简体   繁体   English

我如何告诉RxSwift无论成功或失败都要做某事

[英]How can I tell RxSwift to do something regardless of success or fail

I have a method on a class that calls a service, it uses the response from that service to pass an ID into another service, making a second call. 我在调用服务的类上有一个方法,它使用该服务的响应将ID传递给另一个服务,从而进行第二次调用。

If either of these fail or when the sequence is completed, I'd like to call another function self.showHomeScene() 如果这些失败之一或当序列完成时,我想调用另一个函数self.showHomeScene()

   private func getPropsForHomeScene() {

        profileService.fetchCurrentUser()
            .map { $0.company }
            .flatMap(companyService.fetchCompany)
            .distinctUntilChanged()
            .subscribe(onNext: { company in
                 self.showHomeScene()
            }, onError: { err in
                print(err.localizedDescription)
            }).disposed(by: disposeBag)
    }

Currently I do it in the subscribe block, however this does not get called in the event of an error. 目前,我在subscribe块中执行此操作,但是在发生错误时不会调用它。 It's important this action is called after the first 2 operations. 在前两个操作之后调用此操作很重要。

For this and questions like it, you want to outline all the reasons to perform this output and make them inputs to the stream in question. 对于此问题以及类似的问题,您想概述执行此输出的所有原因,并将它们作为输入到相关流中。

You want the showHomeScene() method to be called when the first call fails or when the second call emits a stop event. 您希望在第一个调用失败或第二个调用发出stop事件时调用showHomeScene()方法。

private func getPropsForHomeScene() {
    let currentUser = profileService.fetchCurrentUser()
        .share(replay: 1)

    let company = currentUser
        .map { $0.company }
        .flatMap { companyService.fetchCompany($0) }

    let currentUserFailed = currentUser
        .materialize()
        .map { $0.error }
        .filter { $0 != nil }
        .map { _ in }

    let companyStopped = company
        .materialize()
        .filter { $0.isStopEvent }
        .map { _ in }

    Observable.merge(currentUserFailed, companyStopped)
        .subscribe(onNext: {
            self.showHomeScene()
        })
        .disposed(by: disposeBag)
}

I notice you don't do anything with the actual company or current user objects that get fetched. 我注意到您对获取的实际公司或当前用户对象不做任何事情。 That doesn't affect this subscribe of course but I expect you will want to subscribe to currentUser and company to do something with them as well. 这当然不会影响此subscribe ,但是我希望您也希望订阅currentUsercompany也可以对它们进行操作。 In that case, you should put a share on the company stream just like it's already on the currentUser stream. 在这种情况下,您应该像在currentUser流上一样在公司流上share

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM