Snake
Snake

Reputation: 14648

ViewModel with multiple fragments

I am just thinking about MVVM when it comes to bottom navigation view.

In this case it is one activity which has multiple fragments. If I use the ViewModel then the view model will hold the data for all fragments, right? Wouldn't this cause memory leaks or be bad for performance?

If I don't use the view model then I would be only holding one single Fragment data at a time.

Am I missing something?

Upvotes: 2

Views: 1385

Answers (1)

danypata
danypata

Reputation: 10175

There are multiple ways to implement this. Keep in mind, ViewModel doesn't have to be used only by Activity, it can be used by a Fragment or even a custom View.

In your case, if you have multiple fragments, you can create a ViewModel for each of them (if they are different off course).

The only thing that will kind of go out of MVVM pattern is the communication between fragment and activity.

If you still want to give the ViewModel the responsibility of telling the activity when to replace/remove/change a fragment, you can define an interface in each model (or a general interface) that will act as a callback, and you can set this callback on your ViewModel in onAttach or wherever fits for you.

Now your fragment, can pass the responsibility of notifying the activity to the ViewModel. I think this is one way of getting close to the MVVM patter in the case of Activity/Fragment communication, without to much trouble.

Upvotes: 2

Related Questions