0

I'm trying to use android live data to observe completion status of an async task in my viewmodel from my fragment. So i considered using ObserveOnce from this post 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()
}

})
}

The problem here is that this observeOnce is called immediately after initilization, and is always showing false.

I dont understand what is wrong here!!

Surendar
  • 239
  • 2
  • 12

1 Answers1

0

You actually set a value for your status which will be emitted as soon as the observer will have an active state.

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.

Do not set the initial value unless you need a default to start with.

Ionut Negru
  • 6,186
  • 4
  • 48
  • 78