问题
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