ViewModel class:
// Update the userInformation and returns Boolean if the operation succeed
val res = viewModelScope.async {
accountRepository.update(
userId,
firstName,
lastName,
birthDate,
photoUrl
)
}
// This should execute
// But the result is always false and go to the else part.
if (res.await()) {
...
} else {
// But it always goes here
...
}
The update function in my repository is executing and I can see the changes in the Firestore, there is no problem. But the result is always false and the ViewModel gives a wrong state in my view and I don't like it. I think the problem is in the withContext part. I don't understand it completely but maybe you can give me insights on how to solve this problem. I
This is the code for my AccountRepository class:
// Account Repository
// Update the user information
suspend fun update(
userId: String,
firstName: String,
lastName: String,
birthDate: String,
avatarUrl: String
): Boolean {
return withContext(dispatcher) {
// This will be true for now
var isSuccess = true
// Parsing the date string "01/01/2000" to a date object
val date = SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(birthDate)
// Creating an instance of calendar object
val calendarDate = Calendar.getInstance()
// Set the time with the date variable
calendarDate.time = date!!
// Check if the user is in the right age to use the application
// User should be 12 years old and above to access this app
if (Calendar.getInstance().get(Calendar.YEAR)
.minus(calendarDate.get(Calendar.YEAR)) >= 12
) {
// Create a map to update fields in the firebase
val updateUserMap = mapOf<String, Any>(
"avatarUrl" to avatarUrl,
"firstName" to firstName,
"lastName" to lastName,
"birthDate" to birthDate,
"dateModified" to Utils.getTimeInMillisUTC()
)
// Execute the query in fireStore
// I'm using ktx gradle library
// This line executes. It reflects the changes in the fireStore
val result = userCollectionRef
.document(userId)
.set(updateUserMap, SetOptions.merge())
.await()
// The variable will be changed to false when the result is null
// Meaning that the query is not successful
if (result == null) {
isSuccess = false
}
}
// Return the variable after all operations
isSuccess
}
}
CodePudding user response:
The variable will be changed to false when the result is null Meaning that the query is not successful
I think this is where you're wrong. From the docs, it seems document.set()
just returns a task that will finish when the query finishes, but it doesn't say that null
will be used as a marker of failure.
Also, the await function you're using will represent the Task
failures as exceptions thrown (which is quite common in coroutines, we usually treat failures in suspend functions just like failures in other functions).
If you want to handle errors, you should probably use try-catch
instead of if (result == null)
.