Last active
May 19, 2017 01:28
-
-
Save cbeyls/988ddfa23c723a1b0be4405e7b36b03e to your computer and use it in GitHub Desktop.
Lifecycle-aware Loader delivering results from a LiveData source
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
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