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

Bacho Kurtanidze

10/28/2019, 9:46 AM
hey guys, how do you normally handle loading state change, do you create progress bar in view/fragment before executing a network call and hiding it when you get response or do you create a wrapper class like this, setting up LiveData for it in view model and then handling its state change in view
p

pietro.scarampella

10/28/2019, 9:55 AM
In my project I use an hybrid approach In the ViewModel there is a LiveData for the network status and one for the payload. Now if the data is fetched from both network and db i use the google NetworkBoundResource, that way both payload and loading status is carried in one object in a livedata that I'll map in order to dispatched on the 2 livedata on the VM. If the call is only from network I usually handle with a suspend function. So in the ViewModel i just update the network status to loading when i start the request and then update it at the end of the call.
t

tseisel

10/28/2019, 10:01 PM
I'm currently using such a sealed class:
Copy code
sealed class ApiResponse<T> {
    object Loading : ApiResponse<Nothing>()
    class Success<T>(val data: T) : ApiResponse<T>()
    class Error(error: Throwable) : ApiResponse<Nothing>()
}
This way, you can check which implementation you have received from
LiveData
and update UI accordingly, having only state (data or error) that is relevant.
a

Aslam Hossin

10/29/2019, 2:14 AM
If you use RxJava them you can use global
SingleTransformer
for
ViewModel
by adding compose operator in your stream and manage it from your base
ViewModel
through UI component like
Activity
or
Fragment
. On the other hand, if you use
coroutines
then use a Sealed
class
for managing your stream.