-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
47 changes: 47 additions & 0 deletions
47
lives/src/main/java/se/ingenuity/lives/DistinctMutableLiveData.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))); | ||
} | ||
} |