Room LiveData fires twice with one stale emission

蹲街弑〆低调 提交于 2020-05-29 10:28:49

问题


This issue was originally observed in a project with MVVM architecture (single activity / multiple fragments) when performing an insert/delete operation to the database and then navigating back to the home fragment. The home fragment then resubscribes to the LiveData in the home ViewModel and LiveData emits twice:

  • One incorrect stale event corresponding to before the database operation
  • A second correct event corresponding to after the database operation

I have created a very simple example project to demonstrate the issue (no MVVM or multiple fragments in example). Here is an animated GIF of the example app

In the example app you can observe the stale event using the following steps:

  • Subscribe to Room LiveData with OBSERVE button
  • Unsubscribe from LiveData with UNOBSERVE button
  • Insert element into Room database with ADD button
  • Subscribe to Room LiveData with OBSERVE button

Then it can be seen that two events are fired. The first is stale.

Might someone know how to ensure that only one correct event is fired after re-subscribing to LiveData?

Note: See "3. Resetting an existing observer" for background on how LiveData can be handled in a single activity/multiple fragment architecture. I use this approach and it led to this issue.

来源:https://stackoverflow.com/questions/52415225/room-livedata-fires-twice-with-one-stale-emission

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!