What is the Correct way to use Live data in MVVM if I need to reload data after some params change?

  android, android-livedata, mvvm

I have a project that part of it uses MVVM Architecture ,,I use a repo to get the data from backend like this :

private val spotlights: MutableLiveData<List<SpotlightModel>> = MutableLiveData()

fun getSpotLight(segmentId: String, segmentType: String): MutableLiveData<List<SpotlightModel>>? {

    mProvider.getSpotLight(
            segmentType = segmentType,
            adType = TYPE_SPOT_LIGHT,
            segmentId = segmentId,
            topics = application.profileManger.topicsIds,
            publishers = application.profileManger.publisherIds,
            debug = application.debugFlag,deviceId = application.idfa)
            .enqueue(object : Callback<List<SpotlightModel>> {
                override fun onResponse(call: Call<List<SpotlightModel>>, response: Response<List<SpotlightModel>>) {
                 
                    if (response.isSuccessful) {
                        spotlights.postValue(response.body())
                    }
                }

                override fun onFailure(call: Call<List<SpotlightModel>>, t: Throwable) {
         
                    spotlights.postValue(null)
                }

            })
    return spotlights
}

Then in the viewmodel I do this ::

class SpotlightViewModel(val application: NewsApplication) :ViewModel() {

var segmentType: String=""
var segmentId:String=""

val repository=SpotlightRepository(application)
var spotslightsLiveData=repository.getSpotLight(segmentId,segmentType)!!

     //if I didn't add this method the data doesn't comeback
fun getSpotLights() {
    spotslightsLiveData= repository.getSpotLight(segmentId,segmentType)!!
}}

I observe it like this

  fun getSpotlights(s_id:String, s_type:String){
    spotlightViewModel?.segmentId=s_id
    spotlightViewModel?.segmentType=s_type
    
    spotlightViewModel?.spotslightsLiveData?.removeObservers(viewLifecycleOwner)
    spotlightViewModel?.spotslightsLiveData?.observe(viewLifecycleOwner, Observer
    
    { spotlightList ->
        if (spotlightList.isNullOrEmpty()) {
            newNewsAdapter?.spotLights = null
            newNewsAdapter?.notifyItemChanged(0)
        }
        else if (spotlightList.isNotEmpty()) {
            newNewsAdapter?.spotLights = spotlightList
            newNewsAdapter?.notifyItemChanged(0)
        }
    })  
           spotlightViewModel?.getSpotLights() }

This code works fine but observer is called many times..also can I use a switch map here if yes how?? Thanks in advance 🙂

Source: Android Questions

LEAVE A COMMENT