1

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.

Alon Shlider
  • 1,187
  • 1
  • 16
  • 46

2 Answers2

1

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Quentin vk
  • 313
  • 3
  • 9
0

we can create observer for return values from second fragment using popBackStack()

In firstFragment use this for observer :-

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val navController = findNavController()
    navController.currentBackStackEntry?.savedStateHandle?.getLiveData<String>("key")
        ?.observe(viewLifecycleOwner) {
          
        }
}

In secondFragment use this code

val navController = findNavController()
    navController.previousBackStackEntry?.savedStateHandle?.set("key", "you press back button")
    navController.popBackStack()
Hamza Rasheed
  • 179
  • 1
  • 2