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.
navController?.getBackStackEntry(R.id.loadCredits)?.lifecycle?.run{
addObserver(LifecycleEventObserver { _, event ->
// Handle life cycle events
if(event == Lifecycle.Event.ON_DESTROY){
// Code to run when dismissed/destroyed
}
})
}
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.