epic
epic

Reputation: 1443

When should i remove livedata observer on android?

I am observing a list in firestore using LiveData . This observations is dependent on another authentication LiveData.

Should i remove the old LiveData observer before creating the new one? What will happen if i don't?

Currently i am removing the observer using next code but i can simplify it greatly if i won't need to since i do the same all over my code

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
...

//Authentication observer which is the ItemAuto dependent
viewModel.auth.observe(viewLifecycleOwner, Observer {auth ->
            updateUserItemAutoLiveData(auth)
        })
}


private fun updateUserItemAutoLiveData(auth: Auth) {
        if (!auth.uid.isNullOrEmpty()) {

            removeUserItemAutoObservers()

            itemAutoLiveDate = viewModel.getUserItemAutoLiveData(auth.uid)

            itemAutoLiveDate!!.observe(viewLifecycleOwner, Observer {
                if (it != null) {
                    if (it.data != null) {
                        itemAutoCompleteAdapter.submitItemAuto(it)
                    } 
                }
            })

        } else {
            removeUserItemAutoObservers()
        }
    }

private fun removeUserItemAutoObservers() {
    if (itemAutoLiveDate != null && itemAutoLiveDate!!.hasObservers()) {
        itemAutoLiveDate!!.removeObservers(this)
    }
} 

ps: i am using Doug Stevenson tutorial which is great!

Upvotes: 4

Views: 9415

Answers (1)

Franz Andel
Franz Andel

Reputation: 1691

If you are using observe method, LiveData will be automatically cleared in onDestroy state.

Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed.

More information can be found here

You need to remove livedata manually only if you use observeForever method. The reason why you need to remove it manually is because when you use observeForever method, you don't specify the lifecycle of it.

Upvotes: 11

Related Questions