Issue
I am trying to make a function removeCategory(categoryAddress: String) in my Firebase Repository which removes the given node from Realtime Database and emits the appropriate result String as Loading, Success or Some Error occurred: [error_message] in a flow. Although the given node gets deleted from the Database successfully I am not receiving Success message.
This is my function inside repo:--
override fun removeCategory(categoryAddress: String)= flow {
val response = StatusString()
realtimeRootRef.child(categoryAddress).ref.removeValue().addOnSuccessListener {
response.status = "Success"
}.addOnFailureListener{
response.status = "Some Error occurred : ${it.message}"
}
emit(response)
}
And this is my ViewModel code where I am calling that function to remove node = remove_testing :--
init {
viewModelScope.launch {
repository.removeCategory("remove_testing").collectLatest {
Log.d(TAG,"statusString : ${it.status}")
}
}
}
This is my StatusString class:--
data class StatusString(
var status: String = "Loading"
)
This is my Logcat:-- Image
The node is getting deleted successfully but I am not able to get the "Success" message in ViewModel. What should I do to receive a success or failure message from the Flow?
Solution
Since you're using Kotlin, the best option that you have would be to use Kotlin Coroutines and not listeners. So in code, your operation should look like this:
fun removeCategory(categoryAddress: String) = flow {
val response = StatusString()
try {
realtimeRootRef.child(categoryAddress).ref.removeValue().await()
response.status = "Success"
} catch (it: Exception) {
response.status = "Some Error occurred : ${it.message}"
}
emit(response)
}
There are also other ways in which you can achieve that:
Answered By - Alex Mamo
Answer Checked By - Mildred Charles (JavaFixing Admin)