Problem
There is a settings screen (SettingsActivity
) with about 10 text fields and 3 buttons. The text fields, which on onClick
open a dialog to insert/edit text, has its contents saved in the SharedPreferences
. The buttons do async requests to retrieve contents and save elsewhere. During the requests, a dialog is shown to notify the progress.
Initial solution
DataRepository
Basically a wrapper for the SharedPreferences that has 10 getters and 10 setters, one for each field. On get[field_name]
, the DataRepository
gets the value from the SharedPreferences
and on set[field_name]
, it commits to the SharedPreferences
.
ViewModel
A ViewModel
which has 10 MutableLiveData
objects, one for each field. This class implements the LifecycleObserver
to know about the SettingsActivity
lifecycle so it could load the fields from the repository on onCreate
and save the fields to the repository on onDestroy
.
There are also 3 methods to do the 3 async requests that are fired by the 3 buttons mentioned. Each method receives an OnRequestProgressListener
instance, that is passed to the class that makes the async request to be used to notify the view about the progress.
View
An activity with 10 fields, that observes the 10 MutableLiveData
from the ViewModel
. On onClick
of each field, a dialog is opened to edit/insert text. On the onPositiveButton
of the dialog, the observer of the corresponding field is called.
The activity implements the OnRequestProgressListener
to show and hide dialogs accordingly to the async requests progress.
Initial solution problem
The design described above doesn't seem to be correct. I can point out some:
- 10
MutableLiveData
in theViewModel
; - 10 getters and 10 setters in the
DataRepository
; - A repository for
SharedPreferences
. - The
ViewModel
receives listeners to pass to the classes that do the async requests which use these listeners to notify the view. All with theViewModel
in the middle.
Correct solution
Is that the correct solution? If not, which I believe it isn't, how should be designed the correct solution?
from How should be implemented the ViewModel for an activity with many fields
No comments:
Post a Comment