Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Lifecycle-aware Loader delivering results from a LiveData source
package be.digitalia.common.loaders;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.LifecycleRegistry;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
public abstract class LifecycleLoader<T> extends Loader<T> implements LifecycleOwner {
private final LifecycleRegistry registry = new LifecycleRegistry(this);
public LifecycleLoader(Context context) {
super(context);
getLiveData().observe(this, new Observer<T>() {
@Override
public void onChanged(@Nullable T data) {
deliverResult(data);
}
});
registry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
@Override
protected void onStartLoading() {
registry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
@Override
protected void onStopLoading() {
registry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
}
@Override
protected void onReset() {
registry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
}
@Override
public Lifecycle getLifecycle() {
return registry;
}
@NonNull
protected abstract LiveData<T> getLiveData();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment