rx.tap订阅的按钮已完成

时间:2017-06-10 01:58:13

标签: ios swift reactive-programming rx-swift

我是RxSwift的新手,我正在尝试实现登录facebook功能,这就是我正在做的事情:

loginButton.rx.tap
            .debug("login tapped")
            .flatMap { [weak self] ()->Observable<AccessToken> in
                guard let strongSelf = self else {
                    throw NetworkError.requestCancelled
                }
                return strongSelf.viewModel.loginFacebook(from: strongSelf)
            }
            .flatMap { [weak self] accessToken->Observable<(accessToken: String, userId: String)> in
                guard let strongSelf = self else {
                    throw NetworkError.requestCancelled
                }
                return strongSelf.viewModel.requestUserInfo(token: accessToken)
            }
            .flatMap { [weak self] (accessToken: String, userId: String)->Observable<LoginResult> in
                guard let strongSelf = self else {
                    throw NetworkError.requestCancelled
                }
                return strongSelf.viewModel.authenticate(accessToken: accessToken, userId: userId)
            }
            .catchError({ error -> Observable<LoginResult> in
                return Observable.just(LoginResult.failure(error: error as! NetworkError))
            })
            .subscribe (onNext:{ [weak self] result in
                guard let strongSelf = self else {
                    return
                }

                switch result {
                case .success:
                    // do something with success
                    }
                case .failure(let error):
                    // do something with error
                }
            }, onCompleted: {
                print("rx.tap completed")
            })
            .disposed(by: disposeBag)

当我点击登录按钮然后关闭弹出的Facebook的登录窗口,我对rx.tap的订阅到达onCompleted时,那么当我再次尝试点击按钮时,没有任何反应。我该如何处理这个案子?任何建议都会有所帮助。

1 个答案:

答案 0 :(得分:1)

这是您链条的简化方案:

loginButton.rx.tap
    .flatMap({ (_) -> Observable<Void> in
        throw NSError(domain: "", code: 0, userInfo: [:])
    })
    .catchError({ error -> Observable<Void> in
        return Observable<Void>.just()
    })
    .subscribe()

当您在Observable<Void>.just()块中生成catchError或在其他块中生成类似内容时,它只会触发一次,这就是您收到completed的原因,之后不会发生任何其他事情。我建议将所有代码放入flatMapLatest中。结果代码为:

loginButton.rx.tap
    .flatMapLatest({ _ -> Observable<Void> in
        return Observable<Void>
            .just()
            .flatMap({ (_) -> Observable<Void> in
                throw NSError(domain: "", code: 0, userInfo: [:])
            })
            .catchError({ error -> Observable<Void> in
                return Observable<Void>.just()
            })
    })
    .subscribe()

希望有所帮助

P.S。检查RxSwift开发团队成员的similar answer