新开屏回屏时LiveData值又出现

LiveData Value Reappearing When Returning to Screen After Opening New Screen

问题

当用户点击应用程序的 RecyclerView 单元格中的项目时,我已经从片段中实现了 YouTube 意图。单击事件在 xml 中通过数据绑定处理并传递给绑定 ViewModel,后者将表示单击事件的 LiveData 值传递给片段.

startActivity(YouTubeIntents.createPlayVideoIntentWithOptions(activity, content.id, false, false))    

但是,在触发onBackPressed()关闭从 YouTube 启动的 activity 并返回到原始应用程序屏幕后,YouTube activity 在屏幕旋转时重新出现,就像 YouTube activity 的 finish() 方法尚未被调用。

预计

关闭 YouTubeActivity 后旋转屏幕不会意外触发 YouTubeActivity 重新显示。

尝试过的解决方案

  1. 尝试将传递到 Intent 的上下文从 context 更改为 activity
  2. 从片段中调用 context.startActivity(...) 而不是 startActivity(...)
  3. 向新的 activity 意图添加了一个标志:intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)根据此 answer
  4. 将 YouTube 意图包装在 "headless" 片段(没有 UI 的片段)中,以尝试控制生命周期。

解决方案

这与 YouTube API 无关,而是 Android 架构库组件 LiveData。我正在使用 LiveData 变量来传递点击事件,该事件在屏幕旋转时再次发出。

Jose Alcérreca 在他的 Medium post LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case).

中概述了最佳解决方案

总而言之,Jose 创建了一个 Event class 来跟踪事件是否以 handled.That 方式,当屏幕旋转时 ViewModelLiveData 不会发出对单个事件不再有效的值。