- 원래는 "소스"는
LiveData
Observer
새로운 인스턴스에 의해 모니터링 될 수있다.
- 이
Observer
인스턴스의 경우 소스 LiveData
이 방출되면 필요한 변환을 수행 한 후 "변형 된"새 LiveData
을 통해 백그라운드 스레드를 준비 할 수 있습니다.
LiveData
소스 LiveData
가 활성화 Observer
S를 가진다 상기 Observer
를 부착하고, 소스 LiveData
가 필요할 때에 만 관찰되고 있다는 것을 보장하지 않는 경우들을 분리 할 수 변환.
이 질문은 소스 코드 LiveData<List<MyDBRow>>
을 제공하며 변형 된 LiveData<List<MyRichObject>>
이 필요합니다.다수의 이러한 변환이 필요
class MyRichObjectLiveData
extends LiveData<List<MyRichObject>>
implements Observer<List<MyDBRow>>
{
@NonNull private LiveData<List<MyDBRow>> sourceLiveData;
MyRichObjectLiveData(@NonNull LiveData<List<MyDBRow>> sourceLiveData) {
this.sourceLiveData = sourceLiveData;
}
// only watch the source LiveData when something is observing this
// transformed LiveData
@Override protected void onActive() { sourceLiveData.observeForever(this); }
@Override protected void onInactive() { sourceLiveData.removeObserver(this); }
// receive source LiveData emission
@Override public void onChanged(@Nullable List<MyDBRow> dbRows) {
// set up a background thread to complete the transformation
AsyncTask.execute(new Runnable() {
@Override public void run() {
assert dbRows != null;
List<MyRichObject> myRichObjects = new LinkedList<>();
for (MyDBRow myDBRow : myDBRows) {
myRichObjects.add(MyRichObjectBuilder.from(myDBRow).build());
}
// use LiveData method postValue (rather than setValue) on
// background threads
postValue(myRichObjects);
}
});
}
}
경우, 위의 논리는 다음과 같이 일반적인 될 수 있습니다 :
abstract class TransformedLiveData<Source, Transformed>
extends LiveData<Transformed>
{
private Observer<Source> observer = new Observer<Source>() {
@Override public void onChanged(@Nullable final Source source) {
AsyncTask.execute(new Runnable() {
@Override public void run() {
postValue(getTransformed(source));
}
});
}
};
@Override protected void onActive() { getSource().observeForever(observer); }
@Override protected void onInactive() { getSource().removeObserver(observer); }
protected abstract LiveData<Source> getSource();
protected abstract Transformed getTransformed(Source source);
}
과 주어진 예를 들어 서브 클래스 A는 다음과 같이 보일 수 LiveData
및 Observer
변형 합친 질문에 의해 다음과 같이 보일 수 있습니다.
class MyRichObjectLiveData
extends TransformedLiveData<List<MyDBRow>, List<MyRichObject>>
{
@NonNull private LiveData<List<MyDBRow>> sourceLiveData;
MyRichObjectLiveData(@NonNull LiveData<List<MyDBRow>> sourceLiveData) {
this.sourceLiveData = sourceLiveData;
}
@Override protected LiveData<List<MyDBRow>> getSource() {
return sourceLiveData;
}
@Override protected List<MyRichObject> getTransformed(List<MyDBRow> myDBRows) {
List<MyRichObject> myRichObjects = new LinkedList<>();
for (MyDBRow myDBRow : myDBRows) {
myRichObjects.add(MyRichObjectBuilder.from(myDBRow).build());
}
return myRichObjects;
}
}