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

后端 未结 5 1391
半阙折子戏
半阙折子戏 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:38

    In my opinion using LiveData in servise is comfortable

        class OneBreathModeTimerService : Service() {
            var longestHoldTime = MutableLiveData().apply { value = 0 }
            ...
        }
    

    Then in fragment

         override fun onCreate(savedInstanceState: Bundle?) {
             mServiceConnection = object : ServiceConnection {
    
                override fun onServiceConnected(name: ComponentName, binder: IBinder) {
                    mOneBreathModeService = (binder as OneBreathModeTimerService.MyBinder).service
    
                    mOneBreathModeService!!.longestHoldTime.observe(this@OneBreathModeFragment, androidx.lifecycle.Observer {
                        binding.tvBestTime.text = "Best $it"
                    })
                }
    
                override fun onServiceDisconnected(name: ComponentName) {}
         }
    

    I am not pro in LiveData, but what can be wrong with such approach?

提交回复
热议问题