Manually clearing an Android ViewModel?

后端 未结 12 1049
独厮守ぢ
独厮守ぢ 2020-12-04 18:50

Edit: This question is a bit out of date now that Google has given us the ability to scope ViewModel to navigation graphs. The better approach (rather

12条回答
  •  春和景丽
    2020-12-04 19:24

    In my case, most of the things I observe are related to the Views, so I don't need to clear it in case the View gets destroyed (but not the Fragment).

    In the case I need things like a LiveData that takes me to another Fragment (or that does the thing only once), I create a "consuming observer".

    It can be done by extending MutableLiveData:

    fun  MutableLiveData.observeConsuming(viewLifecycleOwner: LifecycleOwner, function: (T) -> Unit) {
        observe(viewLifecycleOwner, Observer {
            function(it ?: return@Observer)
            value = null
        })
    }
    

    and as soon as it's observed, it will clear from the LiveData.

    Now you can call it like:

    viewModel.navigation.observeConsuming(viewLifecycleOwner) { 
        startActivity(Intent(this, LoginActivity::class.java))
    }
    

提交回复
热议问题