Arun123
Arun123

Reputation: 118

How can we achieve Shared View Model communication between a Fragment and Activity, where the Activity is not the Parent

I am trying to achieve Fragment to Activity communication given that the Activity is not the parent Activity.

So, I have a MainActivity that has a fragment called ContactListFragment, while the add button on the BottomNavigationView of MainActivity is clicked, I am opening another AddContactActivity to add a contact. My requirement is to when I am clicking the save button on the AddContactActivity, I need to initiate a data-sync with server in ContactListFragment. I think the best approach would be to use a Shared View Model for this, but in that Case how should I create the view model so that the lifecycle owner doesn't get changed?

I thought about using the Application Context as the owner but I feel like its an overkill for a task like this, and it may produce some consequences down the line when other modules are added to the project.

So is there a way to efficiently implement this approach? Thanks.

Upvotes: 0

Views: 220

Answers (1)

Sarah Khan
Sarah Khan

Reputation: 866

Write an interface class with object/objects/Data types you need to sync

interface OnSaveClickListener {
    fun onSaveClicked(contact: Contact)
}

Now in ContactListFragment class

class ContactListFragment : Fragment(), OnSaveClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        (activity as AddContactACtivity).mOnSaveClickListener = this
    }

   
    override fun onSaveClicked(contact: Contact) {
        // Whatever you want to do with the data
    }
        
}

In AddContactActivity,

class AddContactActivity {
   var mOnSaveClickListener : OnSaveClickListener? = null

   private void whenYouClickSave(contact: Contact){
       mOnSaveClickListener?.onSaveClicked(contact)
   }

Upvotes: 1

Related Questions