android - onCleared如何运作AndroidViewModel [android-architecture-component]

标签 android mvvm android-architecture-components

我正在使用AndroidViewModel并返回数据流,无论它是Observable还是LiveData,到目前为止一切顺利,我看到ViewModel类中有一个方法,onCleared()文档说

This method will be called when this ViewModel is no longer used and will be destroyed.It is useful when ViewModel observes some data and you need to clear this subscription to prevent a leak of this ViewModel.



我有一种情况,我从改造中返回Single<ApiResponse>,在.map()中做一些ViewModel,然后以Single<ToBeShownOnUiResponse>的形式返回响应,我在View即片段中对此进行了订阅。
我将订户添加到CompositeDisposable,然后清除它的onStop片段。当我从LoginActivity(保持登录/注册/密码重置片段)导航到HomeActivity(保持与其他片段的布局)时,我看不到ViewModel类的onCleared()方法中编写的日志。我正在做错什么,或者我做错了什么。

我的查询是onCleared()对我有什么帮助。我应该在其中编写哪些单独的代码或清理?

用法:
当我需要字符串资源时,我将使用AndroidViewModel(根据xml中存在的字符串资源来格式化一些api响应),而仅需要api调用时,我将使用ViewModel

最佳答案

调用onCleared的一个示例用例是,当您使用ViewModel进行应用内结算时。在这种情况下,很自然地让BillingClient一直保持 Activity 状态(在下面的示例中,我使用Application),例如:

class BillingViewModel(application: Application)
  : AndroidViewModel(application), PurchasesUpdatedListener, BillingClientStateListener {

  private lateinit var playStoreBillingClient: BillingClient

  init {
    playStoreBillingClient = BillingClient.newBuilder(application.applicationContext)
        .enablePendingPurchases()
        .setListener(this).build()
    playStoreBillingClient.startConnection(this)
  }

...

 override fun onCleared() {
    super.onCleared()
    playStoreBillingClient.endConnection()
}

关于android - onCleared如何运作AndroidViewModel [android-architecture-component],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46693933/

相关文章:

c# - 使用 View 模型值的依赖属性

c# - 为什么这个 ListView CheckBox 绑定(bind)到整个 View 模型而不是行项目?

首次更新后 Android LiveData Observer 未激活

android - 异步任务的 ProgressBar Spinner 不起作用

java - 如何通过共享首选项保存菜单项可见性状态?

Android 如何检索动态添加的 Spinner 的值

c# - 如何单击 ListView 项中的按钮?

android - 无法解析 : androidx. 生命周期 :lifecycle-extensions-ktx:2. 0.0-alpha1

android - Firebase 动态链接和 android 导航架构组件

android - 无法在 Linux 上使用 Eclipse 运行 Android AVD