Search code examples
androiddata-bindingandroid-databinding

How to unbind viewModel from activity when it's destroying


I have my miewModel, which I'm injecting to my fragment throw ViewModelProviders.of(activity, viewModelFactory).get(MyViewModel::class.java).

It's work fine on first time of fragment creation, but if I will close my fragment, then I'will get an error "layout must not be null" which points on some of my layouts which I'm using in my fragment.

As I understood, this ishue happend because databinding still have some links to my fragment. So how to unbind it?

class MyFragment: Fragment(), Injectable {
    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory 

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        activity?.window?.changeStatusBarColor(this.requireContext(), R.color.yellow_status_bar)

        val binding: MyLayoutBinding = DataBindingUtil.inflate(inflater, R.layout.my_layout, container, false)
        binding.viewModel = viewModel

        viewModel.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
}
}

ViewModelModule:

@Binds
@IntoMap
@ViewModelKey(MyViewModel::class)
internal abstract fun bindMyViewModel(myViewModel: MyViewModel): ViewModel

Solution

  • To bound ViewModel life cycle to fragment you need to call:

    val vm = ViewModelProviders.of(fragnemt, viewModelFactory)[MyViewModel::class.java]
    

    instead of:

    val vm = ViewModelProviders.of(activity, viewModelFactory)[MyViewModel::class.java]
    

    Don't forget to release resources in ViewModel.onCleared()