0

I have this AppCompatActivity that host a ViewPager containing 3 Fragments now in the AppCompatActivity toolbar I have this ProgressBar that each of the Fragment can turn on/off using the following calls:

@Subscribe(threadMode = ThreadMode.MAIN)
public void onShowProgressBar(OnRequestToShowProgressBarEvent onRequestToShowProgressBarEvent) {
    progressIndicator.setVisibility(View.VISIBLE);
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void onHideProgressBar(OnRequestToHideProgressBarEvent onRequestToHideProgressBarEvent) {
    progressIndicator.setVisibility(View.INVISIBLE);
}

The Fragment are doing work independently and when doing the work they can turn on the ProgressBar and turn it off when finished.

Now it occurred to me that this will fail since Frag_1 can turn on the ProgressBar and Frag_2 can turn it off and still the Frag_1 has not finished working and should have the ProgressBar on but now it´s off right.

How to solve this?

Tord Larsen
  • 2,670
  • 8
  • 33
  • 76
  • Was thinking using a stack like - all "show" go on the stack and all "hide" pop the stack and the ProgressBar is visible as long as the stack can pop – Tord Larsen Jul 30 '17 at 21:31
  • 1
    Instead, do the right thing, move the logic out of all three fragments and have a “presenter” in charge of all the work that only publishes the states when needed. E.g.: when all three are done, hide it, else, while there’s work, it’s visible. The logic belongs outside of the fragments. – Martin Marconcini Jul 30 '17 at 23:23

1 Answers1

0

Answering my own Q I think this might work, following up on Marconcini comment I place the logic outside at where the ProgressBar live like this:

protected ProgressBar progressIndicator;
private final Stack<String> progressBarStack;


@Subscribe(threadMode = ThreadMode.MAIN)
public void onShowProgressBar(OnRequestToShowProgressBarEvent onRequestToShowProgressBarEvent) {
    synchronized (progressBarStack) {
        progressBarStack.push("show");
        progressIndicator.setVisibility(View.VISIBLE);
    }
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void onHideProgressBar(OnRequestToHideProgressBarEvent onRequestToHideProgressBarEvent) {
    synchronized (progressBarStack) {
        progressBarStack.pop();
        if (progressBarStack.empty())
            progressIndicator.setVisibility(View.INVISIBLE);
    }
} 

Here the 3 Frags must promise to hold there end of the bargain to call onHideProgressBar() after they have called onShowProgressBar()

This seems to work but probably there is some cavities I haven't thought of.

Tord Larsen
  • 2,670
  • 8
  • 33
  • 76