architecture-samples icon indicating copy to clipboard operation
architecture-samples copied to clipboard

[todo-mvvm-live] Fragment observe LiveData

Open huaiyan opened this issue 9 years ago • 2 comments

When I use LiveData in a Fragment, something like

getUserName().observe(getActivity(), result-> {
    do something;
}

usually getUserName() is a network request and may or may not get a answer but it will be pretty fast so there is no problem. But when it's a time consuming task such as scan bluetooth devices. User may have already destroy this fragment and switch to another. And then my APP will be corrupt to do something. I slove it by call removeObservers in onDestroy() but is there any more straightforward solution for it? Or it's not recommended to use LiveData in this kind of situation? Thank you

huaiyan avatar Nov 16 '17 08:11 huaiyan

LiveData won't emit your result if the activity is not active. That's the main advantage of LiveData vs other observables.

JoseAlcerreca avatar Nov 22 '17 14:11 JoseAlcerreca

Sorry, but after a long time I found where is my really question is. The LiveData object observe the activity, so after I destroy the fragment the activity is still active, and the LiveData object will try to inform the activity and do something, which make the app corrupt. To address it, I need to make the LiveData observe fragment.

huaiyan avatar Mar 15 '18 02:03 huaiyan