Issue
I am trying to get The liveStatus of authStateListener using Flow Coroutines .But everytime it returns False. Below is the code with which I tried to implement the following.It follows the MVVM pattern.
Code -> FirebaseUserFlow
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)
}
}
}
ViewModel
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()
}
The log above always returns false
Fragment
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")
}
})
}
In the above fragment , In the onActivityCreated the liveData is observed and based on the state it navigates to the Home Fragment .
Solution
Your error is here
FirebaseAuth.AuthStateListener {
auth = it.currentUser
}
trySendBlocking(auth)
You should call offer()
inside the callback.
open class FirebaseUserFlow() {
private val firebaseAuth = FirebaseAuth.getInstance()
@ExperimentalCoroutinesApi
fun getUserInfo(): Flow<FirebaseUser?> =
callbackFlow {
val authStateListener = FirebaseAuth.AuthStateListener {
trySendBlocking(it.currentUser)
}
firebaseAuth.addAuthStateListener(authStateListener)
awaitClose {
firebaseAuth.removeAuthStateListener(authStateListener)
}
}
}
Answered By - Sinner of the System
Answer Checked By - Terry (JavaFixing Volunteer)