2019-04-17 14:21:30 +00:00
|
|
|
package org.thoughtcrime.securesms.util;
|
|
|
|
|
2020-08-19 00:06:26 +00:00
|
|
|
import androidx.lifecycle.MutableLiveData;
|
2019-04-17 14:21:30 +00:00
|
|
|
import android.database.ContentObserver;
|
2020-08-19 00:06:26 +00:00
|
|
|
import androidx.annotation.NonNull;
|
2019-04-17 14:21:30 +00:00
|
|
|
|
|
|
|
import org.thoughtcrime.securesms.database.ObservableContent;
|
|
|
|
|
|
|
|
import java.io.Closeable;
|
|
|
|
|
|
|
|
/**
|
2020-08-19 00:06:26 +00:00
|
|
|
* Implementation of {@link androidx.lifecycle.LiveData} that will handle closing the contained
|
2019-04-17 14:21:30 +00: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;
|
|
|
|
}
|
|
|
|
}
|