BoundService + LiveData + ViewModel best practice in new Android recommended architecture

后端 未结 5 1389
半阙折子戏
半阙折子戏 2020-12-12 15:06

I been struggling a lot thinking about where to place Android Services in the new Android recommended Architecture. I came up with many possible solutions, but I cannot make

5条回答
  •  北海茫月
    2020-12-12 15:44

    What if we bind/unbind to/from service from activity or multiple activities as usual in onStart/onStop, then we have singleton instance that holds Bluetooth related manager (I use nordic lib for ble manager) . That instance is in service so that we can disconnect for example when service is destroyed because ui unbound from it and reconnect to ble when service is created. We also inject that ble manager singleton into viewmodel to make interaction and data listening easier via livedata or rx or similar reactive data provided by ble manager, for example for connection state. This way we can interact from viewmodel with ble, subscribe to characteristics etc and service is there to provide scope that can survive over multiple activities and basically knows when to connect or disconnect. I have tried this approach in my app and so far it works ok.

    Sample project https://github.com/uberchilly/BoundServiceMVVM

提交回复
热议问题