Android上的RXJava2 - 嵌套的completable不会被调用

时间:2018-05-13 10:09:45

标签: kotlin rx-java2 rx-android

我有一个可完成的身份验证方法,我想在登录成功时检索经过身份验证的用户详细信息。

检索后,我想调用onUserAuthenticated方法。

我使用嵌套的可复制(深度为2级)执行此操作,因为我希望将login上收到的授权令牌和用户详细信息都发送到onUserAuthenticated方法。

问题是onUserAuthenticated永远不会被调用。

class LoginViewModel(val emailAuthentication: EmailAuthentication) : ViewModel() {

    val email = MutableLiveData<String>()
    val password = MutableLiveData<String>()

    fun login() {
        emailAuthentication.login(email = email.value!!, password = password.value!!)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    Timber.d("User $email logged in")
                }, { error ->
                    Timber.e(error, "Error logging in $email")
                })
    }
}

class EmailAuthenticationImpl(private val authentication: Authentication,
                            private val userRepository: UserRepository,
                            private val authRepository: AuthenticationRepository
) : EmailAuthentication {

    override fun register(email: String, password: String): Completable {
        return userRepository.register(email, password)
    }

    override fun login(email: String, password: String): Completable {
        // some missing fields validation
        return authRepository.login(email, password)
                .flatMapCompletable { token ->
                    userRepository.getCurrentUser()
                            .flatMapCompletable {
                                Completable.defer {
                                    // FIXME this never gets invoked
                                    authentication.onUserAuthenticated(AuthType.EMAIL, it, token)
                                    Completable.complete()
                                }
                            }
                }

    }

我尝试仅在Completable.defer之前和userRepository.getCurrentUser()之前以及userRepository.getCurrentUser()之前添加authentication.onUserAuthenticated(AuthType.EMAIL, it, token),但代码永远不会到达。

我做错了什么?

0 个答案:

没有答案