【问题标题】:LiveData owner definition potentially causing leak/retainLiveData 所有者定义可能导致泄漏/保留
【发布时间】:2020-08-21 10:53:59
【问题描述】:

我正在开发一个在Service 中使用LiveData 实例的项目。 我们将 Service 初始化为与我们的 Activity 绑定的服务,因此我们使用 bindService() 和 unBindService() 来连接和断开连接。我们分别在活动生命周期的onResume() 和onPause() 中调用这些函数。

class TestActivity: Activity() {
    lateinit var ourService: OurService
    val serviceConnection: ServiceConnection = object : ServiceConnection {
         override fun onServiceConnected(className: ComponentName, service: IBinder) {
            val binder = service as OurService.LocalBinder
            ourService = binder.getService()
            // Does this cause ourService to be retained beyond unbind the only client
            ourService.liveReading.observe(this@TestActivity, Observer {}
         }
    } 

    override fun onResume() {
           Intent(this, OurService::class.java).also { intent ->
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
        }
    }

    override fun onPause() {
         unBindService(serviceConnection)
    }
}

         

我注意到有一种极端情况,即我在 OurService 的 LiveData 属性中获得了不止一个发射。我想知道这是否是因为将所有者设置为活动,该活动在 onPause/onResume 循环中存活,导致服务在 onPause 情况下不会被销毁,因此导致在另一个循环 onPause/ 后将多个观察者分配给 livedata onResume。

【问题讨论】:

  • 您的服务是否通过其onDestroy?

标签: android android-service android-livedata


【解决方案1】:

因为我看不到你的服务代码,所以这里有两点你应该注意

  1. 当你调用 unBindService 并不意味着你的服务会被销毁,你可以在这里查看服务生命周期https://developer.android.com/reference/android/app/Service
  2. 当您致电ourService.liveReading.observe(this@TestActivity, Observer {} 您应该注意到,您正在使用 TestActivity 的 LifecycleOwner。这意味着liveReading 将在 TestActivity 调用 DESTROYED 状态时停止接收数据。在您的情况下,TestActivity 不调用 DESTROYED 状态(只调用 onPause)所以liveReading 仍然接收数据,问题是当您的活动调用 onPause 时会发生什么?这是你的答案

当 LifecycleOwner 未激活时数据发生变化时,它不会 接收任何更新。如果它再次变为活动状态,它将收到 自动最后可用的数据

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 2013-07-23
    • 2019-08-28
    • 1970-01-01
    • 2011-08-14
    相关资源
    最近更新 更多