Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update LiveData value when becoming active #6301

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@
* @param <T> the type of the RealmModel
*/
public class LiveRealmObject<T extends RealmModel> extends LiveData<T> {
// The listener will listen until the object is deleted.
private final T object;

// The listener will listen until the object is deleted.
// An invalidated object shouldn't be set in LiveData, null is set instead.
private RealmObjectChangeListener<T> listener = new RealmObjectChangeListener<T>() {
@Override
Expand Down Expand Up @@ -72,7 +74,7 @@ public LiveRealmObject(@NonNull T object) {
if (!RealmObject.isValid(object)) {
throw new IllegalArgumentException("The provided RealmObject is no longer valid, and therefore cannot be observed for changes.");
}
setValue(object);
this.object = object;
}

// We should start observing and stop observing, depending on whether we have observers.
Expand All @@ -87,7 +89,11 @@ protected void onActive() {
super.onActive();
T object = getValue();
if (object != null && RealmObject.isValid(object)) {
setValue(object);
RealmObject.addChangeListener(object, listener);
} else if (RealmObject.isValid(this.object)) {
setValue(this.object);
RealmObject.addChangeListener(this.object, listener);
}
}

Expand Down