How to Return LiveData from Repository

后端 未结 3 1908
日久生厌
日久生厌 2020-12-22 08:52

I just can\'t see how to chain LiveData from Repo to VM, so I have tried to boil this down to the most simple of example!:

Fragment

         


        
相关标签:
3条回答
  • 2020-12-22 09:23

    Actually If you are maintaining LiveData in repository, I don't think there's a need of separate LiveData in ViewModel as well. You just have to observe the LiveData once from the activity. Then make any changes to repository instance directly. So If I have to show it in your code, It might look something like this.

    1. Activity class: Change makeToast method to observeCurrentName() like this:

      private fun observeCurrentName() {
          vm.getCurrentName().observe(this, Observer{ 
              //Toast here 
          })
      }
      
    2. Your VM:

      class LoginViewModel : ViewModel() {
          ...
      
          fun getCurrentName(): MutableLiveData<String>{
              return repository.getCurrentName()
          }
      
          fun setCurrentName(name: String?){
              repository.setCurrentName(name)
          }
      
          ...
      }
      
    3. Your repository:

      class FirestoreRepository {
      
          private val mCurrentName = MutableLiveData<String>()
      
          fun getCurrentName(): MutableLiveData<String>{
              return mCurrentName
          }
      
          fun setCurrentName(name: String?){
              mCurrentName.value = name //This will trigger observer in Activity
          }
      }
      
    0 讨论(0)
  • 2020-12-22 09:23

    You're changing mCurrentName (the LiveData variable itself as opposed to it's contents) after you start observing it. The guidance seems to be to not use LiveData in Repository layer (use Coroutines/Flow instead for example)....but for now you could have something like following (or perhaps use one of the LiveData Transformations)

    private val mCurrentName = firestoreRepository.currentName()
    
    fun changeText(){
        firestoreRepository.changeText()
    }
    
    0 讨论(0)
  • 2020-12-22 09:33

    No need to change MutableLiveData inside ViewModel. Try to pass whatever Repository send to View. Check below

    class LoginViewModel : ViewModel() {
    
        private val firestoreRepository : FirestoreRepository = FirestoreRepository()
    
        fun getCurrentName(): MutableLiveData<String> {
            return firestoreRepository.getCurrentName()
        }
    
        fun changeText() {
            firestoreRepository.changeText()
        }
    }
    

    And also your FirestoreRepository

    class FirestoreRepository {
    
        private val mCurrentName = MutableLiveData<String>()
    
        fun getCurrentName(): MutableLiveData<String> {
            return mCurrentName
        }
    
        fun changeText() {
            mCurrentName.value = "Button Clicked!!"
        }
    }
    
    0 讨论(0)
提交回复
热议问题