Custom Lifecycle-aware component
suggest changeEach UI component moves through the states in the image. A component can observe those changes:
public class MyLocationListener implements LifecycleObserver {
private boolean enabled = false;
private Lifecycle lifecycle;
public MyLocationListener(Context context, Lifecycle lifecycle, Callback callback) {
this.lifecycle = lifecycle;
...
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void start() {
if (enabled) {
// connect
}
}
public void enable() {
enabled = true;
if (lifecycle.getState().isAtLeast(Lifecycle.State.STARTED)) {
// connect if not connected
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void stop() {
// disconnect if connected
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents