我在从 firebase 获取数据的函数中有一个中介实时数据对象。
这是我的功能:
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")
}
}
}
在我的活动中,我正在观察我的用户中介对象:
private fun observeUser() = viewModel.user.observe(this, Observer {
if(it != null){
Log.i(TAG, "6. Observed User fetched properly.")
}
})
checkIfExistingUser()
当我单击我的登录按钮时调用此函数。但是在日志中我可以看到函数 decomposeDataSnapshots() 被调用了两次,我不知道为什么。请参阅下面的日志结果:
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
如您所见,数字 4 和 5 被调用了两次,我不知道为什么。
我是否以错误的方式使用调解器实时数据?请帮我。