mantc_sdr
mantc_sdr

Reputation: 491

Fragment Inheritance with ViewModel Inheritance

I have two Fragments and two ViewModels with a similar implementation. So, I decided to apply inheritance. So I decided to create a FragmentParent and a ViewModelParent, and then ended up with:

On one side, both parents will be abstract because they have methods to be implemented in different ways. On the other side, both children ViewModels have the common parent's viewmodel methods and also their personal custom methods.

So, viewmodel object has to call some common methods from the FragmentParent but, also, the problem is that each Fragment will call their correspondent viewmodels' custom methods. So, if I declare the viewModel object in the FragmentParent, once I use it in the children to call the custom methos of each correspondent viewmodel, it says error because the viewModel object's type corresponds to the ViewModelParent. As you can see in the image, the methods in colour cannot be called because vM is instance of ViewModelParent and they belong to the custom ViewModels.

enter image description here

A solution could be casting the viewmodel object in each child fragment once I need to call the custom methods, BUT, I guess this is dirty. Any good idea for this approach? Thanks.

Upvotes: 2

Views: 519

Answers (1)

Ddev
Ddev

Reputation: 121

Casting the parent ViewModel to the specific child ViewModel seems to be the best option. It's a common use of casting, I don't see any problem with it. If you're accessing methods of the child ViewModel multiple times inside the child Fragments, you can store the casted ViewModel in a property or variable in each child Fragment. For example, if you're using Kotlin you could do something like this:

//FragmentA
val viewModel = vM as ViewModelA
viewModel.customAmethod()

//FragmentB
val viewModel = vM as ViewModelB
viewModel.customBmethod()

Upvotes: 1

Related Questions