How do I show progress when using coroutines? e.g....
# android
m
How do I show progress when using coroutines? e.g. The code is usually written in the attached way. If I want to show progress, I can start before making the call. But I'm not sure how to end the progress. I ideally want to stop showing the progress when the coroutine ends, but I'm not aware of any such mechanism. I'll have to observe the different possible results that I get from the call and call
stopProgress()
in each of the observers. Is there a better way? 😞 Can I make this generic so I do not have to do this in each and every fragment?
z
Having both start and end calls in the same method where you actually kick off the operation and observe the results, in your UI layer doesn't seem that bad. Showing progress is a UI concern. The less-than-ideal part seems to be that you have to call stop in two different places. To solve this, and to generally make this code easier to reason about, I would make a sealed class for your result that can represent either success or failure, and then have a single LiveData that emits that sealed class. The approach of using multiple LiveDatas for success and failure is not ideal because, like you pointed out, you have to subscribe twice, but also because it's not clear from the type system how the two are related: can they ever both emit? What would that mean? What does it mean if one emits before the other? Making your result a sealed class answers all those questions.
m
Thanks for the quick response, but the way I'm doing the whole flow currently, I'm not sure how to change 😐
Here's the sealed class
z
What part aren't you sure about? Just use
ApiResult
as the return type for
fetchItems
.
m
So you're saying entirely remove the wrapper
safeApiCall
function that returns
Pair
and directly call the existing
private safeApiCall
from the
Repository
?
z
Yep, wouldn’t be any need for
safeApiCall
after that.
m
This is how I changed the functions in each layer. Can you tell if they look right?
image.png
z
Looks good to me
🙂 2
m
Thank you so much for your help!
j
As a side note you should pass
viewLifecycleOwner
instead of
this
when calling
observe
from your fragment.
👍 1
🙂 1