Why LiveData observer is being triggered twice for a newly attached observer

后端 未结 12 2064
北荒
北荒 2020-12-12 18:03

My understanding on LiveData is that, it will trigger observer on the current state change of data, and not a series of history state change of data.

12条回答
  •  粉色の甜心
    2020-12-12 18:32

    I forked your project and tested it a bit. From all I can tell you discovered a serious bug.

    To make the reproduction and the investigation easier, I edited your project a bit. You can find updated project here: https://github.com/techyourchance/live-data-problem . I also opened a pull request back to your repo.

    To make sure that this doesn't go unnoticed, I also opened an issue in Google's issue tracker:

    Steps to reproduce:

    1. Ensure that REPRODUCE_BUG is set to true in MainFragment
    2. Install the app
    3. Click on "add trashed note" button
    4. Switch to TrashFragment
    5. Note that there was just one notification form LiveData with correct value
    6. Switch to MainFragment
    7. Click on "add trashed note" button
    8. Switch to TrashFragment
    9. Note that there were two notifications from LiveData, the first one with incorrect value

    Note that if you set REPRODUCE_BUG to false then the bug doesn't reproduce. It demonstrates that subscription to LiveData in MainFragment changed the behavior in TrashFragment.

    Expected result: Just one notification with correct value in any case. No change in behavior due to previous subscriptions.

    More info: I looked at the sources a bit, and it looks like notifications being triggered due to both LiveData activation and new Observer subscription. Might be related to the way ComputableLiveData offloads onActive() computation to Executor.

提交回复
热议问题