简体   繁体   中英

Handling loading states of multiple threads in Activity

In my Android app i'd like the user to be able to see when a task is running in the background.

These tasks can be either network calls or database operations, running on separate background threads.

There is a single indeterminate ProgressBar in the Activity , which i would like to show if any background tasks are running, and hide it otherwise.

I've searched for solutions to this and people seem to use LiveData for similar purposes.

So i figured i'd create a LiveData in the ViewModel of the Activity that represents the current loading state of the app, something like this:

val loadingState = MutableLiveData<State>()

Whenever i'm starting or finishing a task, i'd post the appropriate value to this LiveData :

// starting background operation
loadingState.postValue(Status.LOADING)

And i'd observe on it from the Activity and show/hide the ProgressBar according to the current state:

loadingState.observe(this, Observer { status ->
    when (status) {
        Status.LOADING -> showProgressBar()
        Status.IDLE -> hideProgressBar()
    }
}

My problem is i don't know how to handle this when there are multiple tasks running on multiple threads.

For example:

  • A task starts and sets the status to LOADING (correct)
  • B task starts (the status is already LOADING so nothing happens) (correct)
  • A task finishes and sets the status to IDLE , however B is still running (wrong)

    The ProgressBar will be hidden even though B is still in progress

  • B task finishes, but the status is already IDLE (wrong)

I thought i could maintain a Collection of LiveData objects (as in a separate LiveData for each task) but it seems really cumbersome.

Is there an idiomatic way to handle this?

(Java answers are welcome as well)

i have a simple idea

in the view model use variable like that

var numberOFThreads = 0

and replace this line

loadingState.postValue(Status.LOADING)

with

if(numberOFThreads == 0){
loadingState.postValue(Status.LOADING)
}else{
numberOFThreads++
}

and
if(numberOFThreads == 0){
loadingState.postValue(Status.IDLE )
}else{
numberOFThreads--
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM