jpgw
jpgw

Reputation: 109

Retaining ViewModel in fragments

I'm collaborating with ViewModel and fragments, and would like to retain my ViewModel for my fragment on rotation change. When passing my Fragment into ViewModelProviders.of() it does not get retained, but when I pass the Activity that the fragment belongs to, it is retained. So is passing the activity how it is supposed to be used? Calling ViewModelProviders.of(this) in Fragment won't retain my ViewModel. Is that expected behavior?

class MainFragment : Fragment() {

    private lateinit var viewModel: MainViewModel

    fun OnXXXXXXXXX {
        // This _will NOT_ retain ViewModel
        viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)

        // This _will_ retain ViewModel
        viewModel = ViewModelProviders.of(activity).get(MainViewModel::class.java)
    }
}

Upvotes: 0

Views: 1501

Answers (1)

Musab Gultekin
Musab Gultekin

Reputation: 363

Yes, its expected behaviour, Look at this content

Fragments can share a ViewModel using their activity scope to handle this communication

If you want to share same ViewModel, use same context. For Example, multiple fragments on same activity:

ViewModelProviders.of(activity)

Upvotes: 1

Related Questions