Search code examples
androidandroid-viewmodelclean-architectureandroid-mvvm

Is it okay to pass activity instance to view model as per clean architecture


I am having a view model and I am passing the instance of activity to it. However, I am not forcing the viewmodel to accept the instance of my activity only, but Android's activity.

So basically, I am using:

class CustomViewModel(val activity: Activity): ViewModel

instead of:

class CustomViewModel(val activity: MyActivity): ViewModel

Does it still violate the clean architecture or its fine to pass the activity this way?

Also, I am using this activity to open up another fragment. So basically my viewmodel is taking care of that logic. In clean architecture, should this kind of logic be part of Activity/fragment itself?


Solution

  • I am having a view model and I am passing the instance of activity to it.

    That is a really bad idea.

    However, I am not forcing the viewmodel to accept the instance of my activity only, but Android's activity.

    That does not significantly improve the idea. Please bear in mind that your viewmodel instance may be used by one, two, or several instances of your activity class, as the device undergoes configuration changes (e.g., screen rotation, dark mode toggle).

    Whatever problem you are trying to solve using this approach can be solved by some other means, such as the viewmodel having a reactive API (e.g., StateFlow) that the UI observes.

    I am using this activity to open up another fragment

    Have your viewmodel emit a state that the activity observes (e.g., StateFlow). The activity can then see if the current fragment is the desired one when the state changes and, if needed, execute a fragment transaction to switch the current fragment to match that state.

    should this kind of logic be part of Activity/fragment itself?

    Yes.