I have this code that increments a value in the database:
override fun incrementQuantity() = flow {
try {
emit(Result.Loading)
heroIdRef.update("quantity", FieldValue.increment(1)).await()
emit(Result.Success(true))
} catch (e: Exception) {
emit(Result.Failure(e))
}
}
This function is called from within a ViewModel class, and then from a composable function I read the response like this:
when(val response = viewModel.incrementResponse) {
is Result.Loading -> showProgressBar()
is Result.Success -> Log.d("TAG", "Quantity incremented.")
is Result.Failure -> Log.d("TAG", response.e.message)
}
This means that in the flow I receive two events, the first one is Loading, and the second one is the data or a failure. My question is:
Is it recommended to do it that way? Or is it better to not using a flow and have something like this:
override fun incrementQuantity(): Result<Boolean> {
try {
heroIdRef.update("quantity", FieldValue.increment(1)).await()
Result.Success(true)
} catch (e: Exception) {
Result.Failure(e)
}
}
And inside the composable:
showProgressBar()
when(val response = viewModel.incrementResponse) {
is Result.Success -> {
hideProgressBar()
Log.d("TAG", "Quantity incremented.")
}
is Result.Failure -> {
hideProgressBar()
Log.d("TAG", response.e.message)
}
}
Are there any downsides when using Kotlin flow?
Here is my incrementResponse object:
var incrementResponse by mutableStateOf<Response<Boolean>>(Response.Success(false))
private set