I have a mediator live data object in a function which fetches data from firebase.
This is my function:
internal fun checkIfExistingUser(instance: User) {
_user.addSource(UserDao().getAll(instance.email)){
_user.value = decomposeDataSnapshots(it)
}
Log.i(SplashActivity.TAG, "3. Value added properly")
}
private fun decomposeDataSnapshots(snapshot: DataSnapshot?): User? {
var user: User? = null
snapshot?.children?.forEach { postSnapshot ->
postSnapshot.getValue<User>()
?.let { user = it }
}
return user.also {
if (it == null){
Log.i(SplashActivity.TAG, "5. User decomposed: New User")
}else{
Log.i(SplashActivity.TAG, "5. User decomposed: Existing User")
}
}
}
On my activity, i am observing my user mediator object as such:
private fun observeUser() = viewModel.user.observe(this, Observer {
if(it != null){
Log.i(TAG, "6. Observed User fetched properly.")
}
})
This function checkIfExistingUser()
is called when i click on my login button. But in the logs i can see that the function decomposeDataSnapshots() is being called twice and i don't know why. See below the log results:
2020-05-20 18:38:51.677 3236-3236/com.th3pl4gu3.locky I/Splash_Activity_Debug: 3. Value added properly
2020-05-20 18:38:51.918 3236-3236/com.th3pl4gu3.locky I/Splash_Activity_Debug: 4. Decomposition Started
2020-05-20 18:38:51.918 3236-3236/com.th3pl4gu3.locky I/Splash_Activity_Debug: 5. User decomposed: New User
2020-05-20 18:38:51.918 3236-3236/com.th3pl4gu3.locky I/Splash_Activity_Debug: 4. Decomposition Started
2020-05-20 18:38:51.918 3236-3236/com.th3pl4gu3.locky I/Splash_Activity_Debug: 5. User decomposed: New User
As you can see, the number 4 and 5 is being called twice and I don't know why.
Am I using the mediator live data in the wrong way? Please help me.