
Observe Android Dialog Lifecycle
I was recently tasked with refreshing a user’s credit balance after top-up. To do this, I needed to update the user’s balance once the top-up dialog was dismissed.
My initial thoughts were to use a SingleLiveEvent , to send a response back to the parent fragment, which could have worked in my favor with a little more overkill. So I decided to venture deeper into Android lifecycle & Navigation Architecture where I landed on an unexpected solution.
Let’s break down what this code is doing,
As you can see, it gets a reference to the dialog using the getBackStackEntry by now we assume that your dialog since displayed is in the navigation back-stack, then we attach an observer(LifecycleEventObserver) to its lifecycle.
The LifecycleEventObserver is firing events whenever the Dialog lifecycle changes, so in my case, I needed to run a task once the dialog was dismissed, so I checked if the lifecycle event was Lifecycle.Event.ON_DESTROY however, you could handle any other lifecycle event you wished.
Don’t be shy to criticize my method, may be i can learn a thing or two.