T
T
Tsuzukeru2020-09-20 20:21:01
Android
Tsuzukeru, 2020-09-20 20:21:01

How to implement network request state monitoring in MVVM?

I am writing a simple MVVM application.
The ViewModel has a field of type LiveData where I put the value of the fields of my NetworkState state marker class.

It looks like this:

enum class Status {
    WAITING,
    RUNNING,
    SUCCESS,
    FAILED
}

class NetworkState(val status: Status, val msg: String) {

    companion object {
        val WAITING:NetworkState
        val LOADED: NetworkState
        val LOADING: NetworkState
        val ERROR: NetworkState
        val API_LIMIT_EXCEEDED: NetworkState
        val NO_INTERNET:NetworkState

        init {
            WAITING = NetworkState(Status.WAITING,"Waiting user request")
            LOADED = NetworkState(Status.SUCCESS, "Success")
            LOADING = NetworkState(Status.RUNNING, "Running")
            ERROR = NetworkState(Status.FAILED, "Something went wrong")
            API_LIMIT_EXCEEDED = NetworkState(Status.FAILED, "API limit exceeded")
            NO_INTERNET = NetworkState(Status.FAILED,"No internet connection")
        }
    }
}


For example, if the user did not turn on the Internet, then after catching the error, the following will happen:

_networkState.postValue(NetworkState.NO_INTERNET)
            _networkState.postValue(NetworkState.WAITING)


First, I set LiveData to NetworkState.NO_INTERNET, which causes a callback on the _networkState listener and an error DialogFragment appears.
In the second line of code, I change the state of _networkState LiveData to NetworkState.WAITING, indicating that the application has come to its initial state and is waiting for user actions.

So. It works once. I consistently change the value of LiveData and sometimes it happens that the second value of NetworkState.WAITING does not reach LiveData, which breaks the logic of my application. (ProgressBar spins endlessly). Why is this happening? I'm following someone else's code. Is it generally correct to keep track of application states in the ViewModel?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmtm, 2020-09-20
@Tsuzukeru

because such an implementation of postValue, values ​​are delivered in the main thread until the current one is delivered - subsequent ones are ignored
by LiveData in general a dubious solution, it's better to use ObservableField

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question