Search code examples
androidandroid-architecture-componentsandroid-viewmodel

ViewModel in architect component - android


I have a lot of fragment base architect component. Is this true that I create ViewModel for per fragment? or I should create one ViewModel for all fragment?


Solution

  • Saw many project that uses ViewModel for each Activity, and they pass them to their fragments if needed.

    Same goes for me, but figure out what functions that Activity will do, and then build a ViewModel based on that functions:

    • Activity/Fragments that create an object.

    • Activity/Fragment that fetch a list.

    • Activity/Fragment that deal with Objects, like delete, update.

    You can pass ViewModel to fragments. Also you can use inheritance with your ViewModels.