Starting an async task and make an action only when button clicked if result already available otherwise wait for result and then make action

Issue

I have this code to make an asynchronous call in the background, show a progress bar and start another activity when a button is clicked :

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ....

    actionButton.setOnClickListener(this);

    // call action here
}


@Override
public void onClick(View v) {
    if (v.getId()  R.id.actionButton) {
        setProgressVisibility(VISIBLE);
        new MyActivity.ActionTask().execute(action);
    }
}

private void getAction(Action action) {
    try {
        Call<Action> getAction  api.callAction(model, action);
        Response<Action> response  getAction.execute();
        setProgressVisibility(INVISIBLE);
        if (response.isSuccessful() && response.body() ! null) {
            startAction(response.body());
        } else {
            runOnUiThread(() -> showToast(R.string.error, this));
            logger.error(getResources().getString(R.string.error));
        }
    } catch (IOException e) {
        runOnUiThread(() -> showToast(e.getMessage(), this));
        logger.error(e.getMessage());
        setProgressVisibility(INVISIBLE);
    }
}

private void startAction(Action action) {
    Intent intent  new Intent(this, ActionActivity.class);
    intent.putExtra("action", action);
    startActivity(intent);
}

private class ActionTask extends AsyncTask<Action, Void, Action> {
    @Override
    protected Action doInBackground(Action... action) {
        getAction(action[0]);
        return action[0];
    }
}

I would like to start the asynchronous call as soon as the first activity is displayed in OnCreate to make it look faster for the user when he clicks on the button. So the asynchronous call starts as soon as the activity is created, then when the user clicks the button if the result is already available, the next activity starts, otherwise the progress bar is displayed until a result is available and once the result is ready the second activity starts. What’s the best way to do that?

[by Taboola](https://popup.taboola.com/en/?templatecolorbox&utmsourceangularfix&utmmediumreferral&utmcontentthumbnails-mid:Mid Article Thumbnails:)[by Taboola](https://popup.taboola.com/en/?templatecolorbox&utmsourceangularfix&utmmediumreferral&utmcontentthumbnails-mid:Mid Article Thumbnails:)

[Sponsored Links](https://popup.taboola.com/en/?templatecolorbox&utmsourceangularfix&utmmediumreferral&utmcontentthumbnails-mid:Mid Article Thumbnails:)[Sponsored Links](https://popup.taboola.com/en/?templatecolorbox&utmsourceangularfix&utmmediumreferral&utmcontentthumbnails-mid:Mid Article Thumbnails:)

[Promoted Links](https://popup.taboola.com/en/?templatecolorbox&utmsourceangularfix&utmmediumreferral&utmcontentthumbnails-mid:Mid Article Thumbnails:)[Promoted Links](https://popup.taboola.com/en/?templatecolorbox&utmsourceangularfix&utmmediumreferral&utmcontentthumbnails-mid:Mid Article Thumbnails:)

You May Like

[

CNA

](https://www.channelnewsasia.com/singapore/tradenation-luxury-goods-scam-timeline-couple-pi-jiapeng-siriwipa-pansuk-police-interpol-2841536?cidtaboolaidpaid25042022cnamkt-news_angularfix&tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSDsklIo5uiU0KTJ7vTXAQ#tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSDsklIo5uiU0KTJ7vTXAQ “Timeline: How a couple fled Singapore after millions were lost in Tradenation luxury goods scam”)Timeline: How a couple fled Singapore after millions were lost in Tradenation luxury goods scamCNA

Undo

[

Dubai Hotels | Search Ads

](https://gain-an-intl-dubai-hotels-ace.fyi?reftaboola-angularfix&subidangularfix&subid21661-dubaihotels-taboola-all&tbid1353010&tbclicksysclick&compkeycheap+hotels+in+Dubai&rskeyDubai+Hotels+Might+Actually+Surprise+You&tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSC1uFYok46k4-iNpYMO#tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSC1uFYok46k4-iNpYMO “Dubai Hotels Might Actually Surprise You”)Dubai Hotels Might Actually Surprise YouDubai Hotels | Search Ads

Undo

[

Drain – Pipe Cleaning

](https://r.verifysearches.com/d8435411-fd63-49b2-9ab7-b211cebbbe5f?siteangularfix&titleTricks+to+Clean+Your+Drain+Might+Be+Simpler+Than+Ever&platformDesktop&campid19488629&creative3436912494&tnhttp%3A%2F%2Fcdn.taboola.com%2Flibtrc%2Fstatic%2Fthumbnails%2Fbc0793f636785eb3e2c8d8e445eca26e.png&sid1489792&tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSDX11ko9dD788jbvM5p&tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSDX11ko9dD788jbvM5p#tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSDX11ko9dD788jbvM5p “Tricks to Clean Your Drain Might Be Simpler Than Ever”)Tricks to Clean Your Drain Might Be Simpler Than EverDrain – Pipe CleaningLearn More

Undo

Solution

onCreate: start the task

AsyncTask: when the task finishes, check if the user has already clicked on the button. If so, start the next activity. If not, store the result of the task, or just a flag if no result needed.

onClick: Check if the task is done. If so, start the next activity. If not, show the progress indicator, and set a flag indicating the user has clicked the button.

Answered By – nasch

Leave a Comment