Search code examples
androidkotlinandroid-lifecycleandroid-architecture-componentsandroid-livedata

Android LiveData observe is called multiple times


I have a BaseActivity which has a MutableLiveData field as below

val refInfoLiveData: MutableLiveData<RefInfo?> by lazy { MutableLiveData<RefInfo?>() }

A network call is made to populate this MutableLiveData field when onStart method of the BaseActivity is called.

I also have a couple of Fragments which are parts of an Activity that inherits the BaseActivity.

In one if these fragments I am making another call in onResume method of the fragment as below

    (activity as BaseActivity).refInfoLiveData.observe(this, Observer {
        it?.let { refInfo ->
            adapter?.setRefInfo(refInfo)
        }
    })

When the fragment is created for the first time observe only called once but the fragment goes to background then comes back it is called multiple times and that is causing issues.

What could be the reason of this problem and how can I solve it?

Any help would be appreciated.


Solution

  • That's because you are supposed to be using observe(viewLifecycleOwner, Observer { ... inside onViewCreated.

    import androidx.lifecycle.observe
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    
        (activity as BaseActivity).refInfoLiveData.observe(viewLifecycleOwner) { refInfo ->
            refInfo?.let { adapter.setRefInfo(it) }
        }
    }
    

    Currently you'll have an infinite number of subscribers if you put the app in background then bring it foreground an infinite number of times.