2019-04-17 10:21:30 -04:00
|
|
|
package org.thoughtcrime.securesms.util;
|
|
|
|
|
2020-08-19 10:06:26 +10:00
|
|
|
import androidx.lifecycle.MutableLiveData;
|
2019-04-17 10:21:30 -04:00
|
|
|
import android.database.ContentObserver;
|
2020-08-19 10:06:26 +10:00
|
|
|
import androidx.annotation.NonNull;
|
2019-04-17 10:21:30 -04:00
|
|
|
|
|
|
|
import org.thoughtcrime.securesms.database.ObservableContent;
|
|
|
|
|
|
|
|
import java.io.Closeable;
|
|
|
|
|
|
|
|
/**
|
2020-08-19 10:06:26 +10:00
|
|
|
* Implementation of {@link androidx.lifecycle.LiveData} that will handle closing the contained
|
2019-04-17 10:21:30 -04:00
|
|
|
* {@link Closeable} when the value changes.
|
|
|
|
*/
|
|
|
|
public class ObservingLiveData<E extends ObservableContent> extends MutableLiveData<E> {
|
|
|
|
|
|
|
|
private ContentObserver observer;
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void setValue(E value) {
|
|
|
|
E previous = getValue();
|
|
|
|
|
|
|
|
if (previous != null) {
|
|
|
|
previous.unregisterContentObserver(observer);
|
|
|
|
Util.close(previous);
|
|
|
|
}
|
|
|
|
|
|
|
|
value.registerContentObserver(observer);
|
|
|
|
|
|
|
|
super.setValue(value);
|
|
|
|
}
|
|
|
|
|
|
|
|
public void close() {
|
|
|
|
E value = getValue();
|
|
|
|
|
|
|
|
if (value != null) {
|
|
|
|
value.unregisterContentObserver(observer);
|
|
|
|
Util.close(value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public void registerContentObserver(@NonNull ContentObserver observer) {
|
|
|
|
this.observer = observer;
|
|
|
|
}
|
|
|
|
}
|