Skip to content

Commit

Permalink
DistinctMutableLiveData
Browse files Browse the repository at this point in the history
  • Loading branch information
c-b-h committed Apr 24, 2020
1 parent 2d1cd5e commit b475e26
Showing 1 changed file with 47 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package se.ingenuity.lives;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;

import java.util.concurrent.atomic.AtomicBoolean;

public class DistinctMutableLiveData<T> extends LiveData<T> {
@NonNull
private final Object dataLock = new Object();

@NonNull
private final AtomicBoolean firstTime;

public DistinctMutableLiveData() {
super();
firstTime = new AtomicBoolean(true);
}

public DistinctMutableLiveData(T value) {
super(value);
firstTime = new AtomicBoolean(false);
}

@Override
public void setValue(T value) {
if (canUpdate(value)) {
super.setValue(value);
}
}

@Override
public void postValue(T value) {
synchronized (dataLock) {
if (canUpdate(value)) {
super.postValue(value);
}
}
}

private boolean canUpdate(T currentValue) {
T previousValue = getValue();
return (firstTime.compareAndSet(true, false)
|| (previousValue == null && currentValue != null)
|| (previousValue != null && !previousValue.equals(currentValue)));
}
}

0 comments on commit b475e26

Please sign in to comment.