How to Create an Auto-Dismissing Dialog

After a long break, I’m back here to share a new “how-to” post. We Android developers use dialogs almost in every app. It’s quite easy to create and display a default Android dialog. However, what if you want to create an auto/self-dismissing dialog that stops displaying after a couple of seconds? For such case, I have a very simple solution for you. This solution involves RxAndroid, but don’t worry… You don’t need to know the details of it.

Let me share the code snippet first, then I’ll dive into the explanation:

It’s that short and simple actually. First, I created a non-cancelable AlertDialog, because I want it to be canceled/dismissed only by itself. This is the part that most of Android developers are familiar with. The next part involves Rx as I said, and is a little bit complex. I created an Observable here, which is an Rx object that emits stuff. What and how long it emits are here defined by interval() and takeUntil() methods. In this example, the method interval(...) returns an Observable that emits the current second value after each second starting without any delay. And the method takeUntil(...)  takes a Predicate object for which you have to override test() method. Inside, you have to indicate how long this emission should go on. This method is executed after each period (1 sec in this example). When this method returns true, the emission stops. That’s why in this example when the current second value (the parameter of the test() method) becomes equal to the time-to-live value we set for the dialog, we want it to return true. The method observeOn(...) here tells that the emission is listened on the Android main thread. In the end, we want to consume this observable so that we can automatically dismiss the dialog by listening to the values that observable emits. So, we subscribed to that observable via a Consumer object and overriding its accept() method. This method is called after each period on the main thread. Inside, we updated the message of the dialog with the countdown value and checked if it’s time to dismiss the dialog. When the parameter of the accept() method becomes equal to the dialog’s time-to-live value we set, we dismiss the dialog.

Now, you know how to write a code that automatically dismisses a dialog after given amount of seconds, and at each second it updates the message the dialog displays. If you have any question about anything, please leave a comment.

By the way, you need to add the following dependencies to your “build.gradle” file to be able to use the ReactiveX components:

One comment Add yours

Leave a Reply

Your email address will not be published. Required fields are marked *