What role an Android Service should play in the MVP pattern?

后端 未结 3 752
臣服心动
臣服心动 2021-02-05 23:19

I am developing an Android app that does Human Activity Recognition.

It basically works like that - Service constantly reads the accelerator data and stores the recogniz

3条回答
  •  有刺的猬
    2021-02-06 00:10

    I am in the same situation. Finally I decided to do something like this:

    Activities or Fragments are out of scope, they do not know anything about MVP BUT i am going to use an event bus like Otto to send signals/events, So:

    My classes which extends some kind of Presenter know nothing about Android Context but they will have an MvpView interface, with only onAttachPresenter and onDetachPresenter.

    The class which extends Service will have a Presenter attribute and implements some MvpView interface with onSucess, onError, onStart, onComplete or something like that and same events for Otto (onSucessEvent, onErrorEvent, onStartEvent, onCompleteEvent).

    So when I need to do something the Activity or Fragment will start the service, the service will "start" or talk with the Presenter and when the presenter finish with success will call to mvpView.onSuccess() and store the info inside a local DB with SQLite (storeIO maybe) and finally the Service will invoke Otto and pass the signal (without any data on it), probably onComplete. Finally the signal will be catched by my UI (fragment maybe) and retrieve all the info inside a DB in SQLite.

    So when the onSucess happens the UI will show the latest and best data BUT when onError happens will (at least) show some info (or not if you want) saying to the user "there was a problem but at least you can see something", bot onSuccess and onError will call onComplete after all.

    Do not know if this is the best solution but in this case I think I am not going to deal with Activities or Fragments lifecycle and do not care about onSaveInstance and restore data when the user rotates the device. It will always fetch the latest data inside DB, and if something happens (no internet connection) you can at least show something when you receive the onComplete Signal.

    Some facts I am still thinking:

    • The Presenter won't be a singleton class
    • Presenter knows nothing about Context but yes with MyApplication class
    • What happens if for one screen (Fragment) you have differents service with differents onSuccessEvents? Simply use some kind of action as an ID, to identify them.
    • Never make the Activity Fragment implements the MvpView, you will have to deal with the lifecycle.

提交回复
热议问题