https://kotlinlang.org logo
#android
Title
# android
m

manlan

06/28/2020, 1:04 PM
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

Zach Klippenstein (he/him) [MOD]

06/28/2020, 1:12 PM
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

manlan

06/28/2020, 1:42 PM
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

Zach Klippenstein (he/him) [MOD]

06/28/2020, 1:58 PM
What part aren't you sure about? Just use
ApiResult
as the return type for
fetchItems
.
m

manlan

06/28/2020, 2:18 PM
So you're saying entirely remove the wrapper
safeApiCall
function that returns
Pair
and directly call the existing
private safeApiCall
from the
Repository
?
z

Zach Klippenstein (he/him) [MOD]

06/28/2020, 2:41 PM
Yep, wouldn’t be any need for
safeApiCall
after that.
m

manlan

06/28/2020, 2:53 PM
This is how I changed the functions in each layer. Can you tell if they look right?
image.png
z

Zach Klippenstein (he/him) [MOD]

06/28/2020, 3:23 PM
Looks good to me
🙂 2
m

manlan

06/28/2020, 3:51 PM
Thank you so much for your help!
j

JohnV

06/28/2020, 7:18 PM
As a side note you should pass
viewLifecycleOwner
instead of
this
when calling
observe
from your fragment.
👍 1
🙂 1
2 Views