streetcomplete / StreetComplete

Easy to use OpenStreetMap editor for Android
https://streetcomplete.app
GNU General Public License v3.0
3.87k stars 353 forks source link

Use ViewModels (master) #5530

Open westnordost opened 7 months ago

westnordost commented 7 months ago

This is the master ticket for refactoring to include view models. View models should be used for Fragments and Activities that either have a state that transcends the view lifecycle or access the data layer.

Contributing

As this is a larger undertaking which can be implemented step by step - a Fragment at a time - this ticket shall serve as a master ticket. Whenever you would like to contribute, select a Fragment, post that you are now working on that one here and later post a PR when you are done.

How to

How to find Fragments and Activities that should have view models

Search for activities and fragments that...

  1. have onSaveInstanceState - it means it saves its state manually. This state should be in the ViewModel
  2. by inject() - it means that dependencies are injected which are likely part of the data layer. Data access should be managed by the ViewModel
  3. NOT to be done for now: have something like parentFragment as? Listener ?: activity as? Listener - this pattern is used for communication between fragments. This can be replaced with shared view models, but when using Compose, probably only the top-level fragments will remain as fragments anyway. So, wait with that until using Compose

How to implement ViewModels

ViewModel documentation

If you are like me and learn best by example / by copying. Look in the code for classes named *ViewModel and *ViewModelImpl. For example EditStatisticsViewModelImpl.

This will also give you a good idea in which style ViewModels should be written and what code should go into the ViewModel and what should remain the the View (i.e. the Fragment). The ViewModels job is to supply the view with the data it needs with a convenient interface and data structure, hold this state and also offer an interface to manipulate the data, if applicable.

Advantages

We want to refactor the code to use ViewModels for the following reasons:

(This ticket supsersedes #5070 which also included a lot of discussion.)

westnordost commented 6 months ago

I added view models for

Now, the profile screen all has viewmodels.

westnordost commented 6 months ago

Added viewmodels for everything in the settings screen, the about screen and some controls on the main screen.

westnordost commented 5 months ago

and edit history, which spawned a crictical bug that has been fixed in v57.3