android / architecture-components-samples

Samples for Android Architecture Components.
https://d.android.com/arch
Apache License 2.0
23.44k stars 8.28k forks source link

[GithubBrowserSample] NetworkBoundResource#setValue() called twice after Dao#insert() action. #913

Open Yubyf opened 4 years ago

Yubyf commented 4 years ago

I printed the log after setValue() when inserting User to local database.

Code:

saveCallResult(processResponse(response))
appExecutors.mainThread().execute {
    // we specially request a new live data,
    // otherwise we will get immediately last cached value,
    // which may not be updated with latest results received from network.
    result.addSource(loadFromDb()) { newData ->
        setValue(Resource.success(newData))
        if (newData is User) {
            Timber.tag("NetworkBoundResource")
                    .d("Set value - %s", newData.toString())
        }
    }
}

Log:

2020-10-10 21:14:20.931 D/NetworkBoundResource: Set value - User(login=ianhanniballake, avatarUrl=https://avatars1.githubusercontent.com/u/517315?v=4, name=Ian Lake, company=@google, reposUrl=https://api.github.com/users/ianhanniballake/repos, blog=)
2020-10-10 21:14:20.937 D/NetworkBoundResource: Set value - User(login=ianhanniballake, avatarUrl=https://avatars1.githubusercontent.com/u/517315?v=4, name=Ian Lake, company=@google, reposUrl=https://api.github.com/users/ianhanniballake/repos, blog=)

And I also found that if I wait 50 MS after inserting action, it behaves normally. Like that:

saveCallResult(processResponse(response))
Thread.sleep(50)
...

How can I gracefully avoid this problem of Room and LiveData?