I am popping the backstack on my nav controller on some point in my code -
navController.popBackStack()
The fragment that added that following fragment to the backstack needs to know exactly when that one was popped in order to trigger code following that.
How do I make the first fragment know about it?
I thought about adding a callback as an argument but I doubt it's a good practice.
If you use Koin you can do something like:
class MyActivity : AppCompatActivity(){
// Lazy inject MyViewModel
val model : MySharedViewModelby sharedViewModel()
override fun onCreate() {
super.onCreate()
model.isFragmentPopped.observe(this, Observe{
if(it){
doSomething()
}
}
}
}
Fragment:
class MyFragment : Fragment(){
// Lazy inject MyViewModel
val model : MySharedViewModel by sharedViewModel()
override fun onCreate() {
super.onCreate()
var fragmentX = model.isFragmentXPopped
}
fun backstackPopped{
model.fragmentPopped()
navController.popBackStack()
}
}
ViewModel:
var _isFragmentPopped = MutableLiveData<Boolean>(false)
val isFragmentPopped : LiveData<Boolean>
get = _isFragmentPopped
fun fragmentPopped(){
_isFragmentPopped.value = true
}
Keep in mind that you should keep sharedViewModels as small as possible as they do not get destroyed until the activity is destroyed.