【问题标题】:LiveData Observer Called on initialization & ObserveOnce not workingLiveData Observer 在初始化时调用 & ObserveOnce 不起作用
【发布时间】:2020-05-22 20:06:43
【问题描述】:

我正在尝试使用 android 实时数据从我的片段中观察我的视图模型中异步任务的完成状态。所以我考虑使用这篇文章中的 ObserveOnce LiveData remove Observer after first callback

    // in ViewModel
var status= MutableLiveData<Boolean>()

fun asyncTask(){
// do some async task
asyncTask.addOnSuccessListener{
    status.value = true
}
asyncTask.addOnFaiureListener{
    status.value = false
}
}

// In Fragment

fun startProcess(){
viewmodel.status.value = false
viewmodel.asyncTask
viewmodel.status.observeOnce(viewLifecycleOwner, Observer { it ->
if(it){
Toast.maketext(requireActivity(),"Task Done",Toast.LENGTH_SHORT).maketext()
}else{
Toast.maketext(requireActivity(),"Task Failed",Toast.LENGTH_SHORT).maketext()
}

})
}

这里的问题是这个observeOnce在初始化后立即被调用,并且总是显示为false。

我不明白这里有什么问题!

【问题讨论】:

    标签: android-livedata


    【解决方案1】:

    您实际上为您的状态设置了一个值,该值将在观察者处于活动状态时立即发出。

    If LiveData already has data set, it will be delivered to the observer.
    ...
    When data changes while the owner is not active, it will not receive any updates. If it becomes active again, it will receive the last available data automatically.
    

    除非你需要一个默认值,否则不要设置初始值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多