App Descripion
I'm trying to implement for my first time an Android app with MVP, where a message (taken from a pool of messages) is displayed and it's changed when the user click on the screen. Once all message have been displayed, the process will start over (following the same order of messages). A requirement is to display the same message if the app is closed/reopened. So, we have to implement some implement some store/restore state mechanism in the MVP model.
Here's a basic demo of the app:
MVP Design
I've implemented this MVP for this app as follow:
- The Model takes care of what it will be the next message (it implements the application state).
- The Presenter decides when to ask for the next message (to update the state), depending on the received events from the user (through the View).
- The View decides how to show the actual message and communicates events from the user (clicks on the screen) to the presenter. In addition, since the View is also the
MainActivity
, it takes care to instantiate the Presenter and Model implementations. Finally, it saves the Model state (as aParcelable
) withonSaveInstanceState
(and also restores it).
Some Code
(Partial) View implementation:
class MainActivity : AppCompatActivity(), ViewMVC {
private lateinit var presenter: Presenter
private var model: Model? = CircularModel(LinkedList<State>(Arrays.asList(
State("First"),
State("Second"),
State("Third")
)))
override fun onCreate(savedInstanceState: Bundle?) {
if (savedInstanceState != null) {
model = savedInstanceState.getParcelable("model")
}
presenter = PresenterImpl(this, model!!)
}
override fun onSaveInstanceState(outState: Bundle?) {
outState?.putParcelable("model", model!!)
super.onSaveInstanceState(outState)
}
(Partial) Model implementation:
@Parcelize
class CircularModel constructor(var states: @RawValue Deque<State>?) : Model, Parcelable {
override fun getModelState(): State {
return states!!.peekFirst()
}
override fun getModelNextState(): State {
// Black magic happening here!
return getModelState()
}
}
The Problem / My question
Since Presenter and Model should be "Android agnostic", saving the app state (i.e., the Model object) is taken care by the View. However, this breaks the principle where the View doesn't know the Model. My question is: how to save the Model object, without the View knowing the actual implementation of it? What is the best way to deal with the Model state in this scenario?
Aucun commentaire:
Enregistrer un commentaire