【问题标题】:How to handle Flow Coroutines Asynchronous Behaviour while using API使用 API 时如何处理流协程异步行为
【发布时间】:2020-11-29 06:46:03
【问题描述】:

我正在尝试使用 Flow Coroutines 获取 authStateListener 的 liveStatus。但每次它返回 False。下面是我尝试实现的代码。它遵循 MVVM 模式。

代码 -> Firebase 用户流

open class FirebaseUserFlow() {

    private val firebaseAuth = FirebaseAuth.getInstance()

    private var auth: FirebaseUser? = null


    @ExperimentalCoroutinesApi
    fun getUserInfo(): Flow<FirebaseUser?> =
        callbackFlow {
            val authStateListener = FirebaseAuth.AuthStateListener {
                auth = it.currentUser
            }
            offer(auth)
            firebaseAuth.addAuthStateListener(authStateListener)
            awaitClose {
                firebaseAuth.removeAuthStateListener(authStateListener)
            }
        }

}

视图模型

class AuthViewModel : ViewModel() {


    enum class AuthenticationClass {
        AUTHENTICATED,
        UNAUTHENTICATED
    }

    @ExperimentalCoroutinesApi
    val authenticationState = FirebaseUserFlow().getUserInfo().map {
        Log.d("Tag","The value of the user is $it")
        if (it != null) {
            AuthenticationClass.AUTHENTICATED
        } else {
            AuthenticationClass.UNAUTHENTICATED
        }
    }.asLiveData()


}

上面的日志总是返回false

片段


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

            viewModel.authenticationState.observe(viewLifecycleOwner, Observer {authenticationstate ->
                when (authenticationstate) {

                    AuthViewModel.AuthenticationClass.AUTHENTICATED -> {
                        findNavController().navigate(R.id.action_loginFragmentUser_to_homeFragment)

                        Log.d("TAG","Authenticated")
                    }
                    else ->    Log.d("TAG","Else")

                }

        })

    }

在上面的片段中,在 onActivityCreated 中观察到 liveData 并根据它导航到主页片段的状态。

【问题讨论】:

    标签: android kotlin mvvm firebase-authentication kotlin-coroutines


    【解决方案1】:

    你的错误在这里

    FirebaseAuth.AuthStateListener {
        auth = it.currentUser
    }
    offer(auth)
    

    你应该在回调中调用offer()

    open class FirebaseUserFlow() {
    
        private val firebaseAuth = FirebaseAuth.getInstance()
    
        @ExperimentalCoroutinesApi
        fun getUserInfo(): Flow<FirebaseUser?> =
            callbackFlow {
                val authStateListener = FirebaseAuth.AuthStateListener {
                    offer(it.currentUser)
                }
                firebaseAuth.addAuthStateListener(authStateListener)
                awaitClose {
                    firebaseAuth.removeAuthStateListener(authStateListener)
                }
            }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-28
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 2021-08-28
      • 1970-01-01
      • 2021-06-18
      相关资源
      最近更新 更多