[todo-mvvm-live] Fragment observe LiveData
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
LiveData won't emit your result if the activity is not active. That's the main advantage of LiveData vs other observables.
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.