简体   繁体   中英

Android MVVM 2 ViewModels Sharing 1 Repository with LiveData

I have a question regarding MVVM pattern with Repository.

  • I have an activity that hosts 2 fragments. Let's call them FragmentA and FragmentB .

  • These 2 fragments have their own viewModels like viewModelA and viewModelB .

  • I also have a repository class that serves only local data. No network request. Just a MutableList.

  • FragmentA and FragmentB observe their respective viewModel through LiveData.

//FragmentA Observes viewModelA
viewModelA.cartContent.observe(viewLifecycleOwner, Observer { content ->

})
// ViewModelA exposes cartContent
val cartContent: LiveData<MutableList<Item>> = repository.getContent()
// Repository
private val contentRepository = mutableListOf<Item>()
fun getContent() : LiveData<MutableList<Item>> {
  val data = MutableLiveData<MutableList<Item>>()
  data.value = contentRepository
  return data
}
.
.
.

Now, both viewModels are making changes on the repository that keeps a MutableList. I would like to know if it is possible to observe the changes on the repository that is done by the other viewModel. If so, how?

To be more clear, I want viewModelA to know when viewModelB modifies the list in repository. Can viewModelA observe data in repository so that when viewModelB modifies it, it propagates to viewModelA as well?

I would rather not use a shared viewModel. I would also prefer to solve it with observing LiveData rather than using interfaces

Thank you

// Repository
private val contentRepository = MutableLiveData<List<Item>>(Collections.emptyList())
fun getContent() : LiveData<List<Item>> = contentRepository

fun addContent(item: Item) {
    val list = ArrayList(contentRepository.value!!)
    list.add(item)
    contentRepository.value = Collections.unmodifiableList(list)
}

fun setContent(items: List<Item>) {
    contentRepository.value = Collections.unmodifiableList(ArrayList(items))
}

And

val cartContent: LiveData<List<Item>> = repository.getContent()

And

import androidx.lifecycle.observe

//FragmentA Observes viewModelA
viewModelA.cartContent.observe(viewLifecycleOwner) { content ->

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM