我有一个项目,它的一部分使用MVVM架构,我使用一个repo从后端获取数据,像这样:
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
}
然后在视图模型中我这样做::
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)!!
}}
我是这样观察的
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() }
这段代码工作得很好,但是观察者被调用了很多次,我也可以在这里使用一个开关映射吗?提前感谢:)
可以使用switchMap:
val resultLiveData = paramsLiveData.switchMap { params ->
getLiveDataBy(params)
}