Search code examples
javaandroidasynchronouswaitsnackbar

How do I wait() for the snackbar onDismissed process to finish?


I'm want to start a process after the snackbar onDismissed is completed.

if (snackbar != null){
                    snackbar.dismiss();
                    finish();
                } else {
                    finish();
                }

Since the snackbar onDismissed is asynchronous the activity will finish before the onDismissed task is complete.

snackbar.addCallback(new Snackbar.Callback() {

            @Override
            public void onDismissed(Snackbar snackbar, int event) {
                if (event != DISMISS_EVENT_ACTION) {
                    // Some work to be done.
            }

I realise I can call finish() in onDismissed but there are other actions which cause the snackbar to dismiss and I don't want them to finish the activity. Is there a way to wait for the snackbar process to finish before continuing through code?


Solution

  • Look at the Android Documentation for Snackbar. You can use DISMISS_EVENT_MANUAL to signify that the dismiss of a snack bar coming from a dismiss() call.

    snackbar.addCallback(new Snackbar.Callback() {
    
            @Override
            public void onDismissed(Snackbar snackbar, int event) {
                if (event == DISMISS_EVENT_MANUAL) {
                    // Some work to be done.
                    activity.finish()
                }
            }
    

    Another option is that you extend the Snackbar.Callback(). Something like

    class MyCallback extends Snackbar.Callback {
          Runnable run;
          @Override
          public void onDismissed(...) {
               // Do something
               if (run) run.run();
          }
    }
    BaseCallback<Snackbar> callback = new MyCallback();
    snackbar.addCallback(callback);
    

    And then do this when you want to finish on dismiss.

    if (snackbar != null){
        callback.run = new Runnable() {
             void run() {
                 finish();
             }
        };
        snackbar.dismiss();
    } else {
        finish();
    }