androidkotlineventsgreenrobot-eventbus

Android/Kotlin replacement for EventBus postSticky()


I am searching for postSticky() method replacement. It is being used for simple passing value to previous Fragment, but thing is that I am using BackStackUtil for navigation so instance() method is being called when returning only if stack gets cleared somehow before getting back.

Previous Fragment is holding List of items, when next Fragment can modify picked item and yet another one can do something else so it is chain of sticky events when each of these is being passed to previous Fragment.
App structure won't let me to apply Coordinator pattern at current stage and also I don't want to attach Bundle to Fragments kept on stack.

I was looking for solutions but I couldn't find any. I also don't want to store values in some static fields or SharedPreferences/Data storage.
I was thinking about shared ViewModel but I don't really like this idea to be honest, so I would appreciate any ideas or just confirmation if shared VM is the only/best way.

Do you have any other ideas?


Solution

  • In your A fragment, before navigating to B fragment, listen to savedStateHandle:

     findNavController()
          .currentBackStackEntry
          ?.savedStateHandle?.getLiveData<Bundle>("DATA_KEY")
          ?.observe(viewLifecycleOwner) { result ->
            // Result from fragment B
        }
    

    In your B fragment, before navigating back, set the data to pass to A fragment:

    findNavController()
        .previousBackStackEntry
        ?.savedStateHandle
        ?.set("DATA_KEY", result)
    

    You can remove the observer using:

    findNavController()
          .currentBackStackEntry
          ?.savedStateHandle?.remove<Bundle>
    

    Note that here the passed type is Bundle (the type in getLiveData<Bundle>) but you can use any type you want.