将Firestore与Android体系结构组件一起使用时出错

时间:2019-05-10 11:22:32

标签: android firebase kotlin google-cloud-firestore android-livedata

我有一个活动,要求用户登录。一旦用户登录,用户详细信息就会上传到Firebase,使用活动中的LiveData可以看到该用户的详细信息。

问题是即使成功上传了数据,LiveData仍显示发生了错误。

活动

class LoginActivity : AppCompatActivity() {

private val RC_SIGN_IN = 123

private val viewModel by viewModel<LoginViewModel>() // Lazy inject ViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_login)
    loginUser()
    observeLoginLiveData()
}


private fun observeLoginLiveData() {
    viewModel.onAuthenticationSuccessful().observe(this, Observer { result ->
        when (result) {
            is Result.Loading -> {
            }

            is Result.Success<*> -> {
                startActivity(Intent(this, MainActivity::class.java))
                finish()
            }

            is Result.Error -> {
                clLogin.showSnackbar(R.string.error_login) {}
                Timber.e(result.errorMessage)
            }
        }
    })
 }
}

ViewModel

class LoginViewModel(val repo: LoginRepository) : ViewModel() {

private val _loginLiveData = MutableLiveData<Result>()
private val loginLiveData: LiveData<Result>
    get() = _loginLiveData

fun onAuthenticationSuccessful(): LiveData<Result> {
    _loginLiveData.value = Result.Loading
    viewModelScope.launch {
        _loginLiveData.value = repo.uploadUserDetails()
    }
    return loginLiveData
 }
}

存储库

class LoginRepository {

suspend fun uploadUserDetails(): Result {
val response = withContext(Dispatchers.IO) {
        val currentUser = FirebaseUtils.getCurrentUser()
        val user = User(currentUser?.displayName, currentUser?.email, currentUser?.photoUrl.toString())

        FirebaseFirestore.getInstance()
            .collection(FirebaseReferences.COLLECTION_USERS)
            .add(user)
    }

    return if (response.isSuccessful) {
        Result.Success("true")
    } else {
        Result.Error("Error uploading user data")
    }
 }
}

我也尝试使用response.isComplete,但每次也会返回false。

我不知道我在这里想念的是什么。任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

如评论中所建议,我更改了代码以等待结果,如下所示,现在我得到了正确的响应:

更改了ViewModel

class LoginViewModel(val repo: LoginRepository) : ViewModel() {

private val _loginLiveData = MutableLiveData<Result>()
private val loginLiveData: LiveData<Result>
    get() = _loginLiveData

fun onAuthenticationSuccessful(): LiveData<Result> {
    _loginLiveData.value = Result.Loading

    viewModelScope.launch {
        repo.uploadUserDetails().addOnCompleteListener {
            if (it.isSuccessful) {
                _loginLiveData.value = Result.Success("true")
            } else {
                _loginLiveData.value = Result.Error("Error uploading user data")
            }
        }
    }
    return loginLiveData
 }
}

更改的存储库

class LoginRepository {

suspend fun uploadUserDetails(): Task<DocumentReference> = withContext(Dispatchers.IO) {
    val currentUser = FirebaseUtils.getCurrentUser()
    val user = User(currentUser?.displayName, currentUser?.email, currentUser?.photoUrl.toString())

    FirebaseFirestore.getInstance()
        .collection(FirebaseReferences.COLLECTION_USERS)
        .add(user)
 }
}