@OnLifecycleEvent(Lifecycle.Event.ON_RESUME) void addLocationListener() { // Note: Use the Fused Location Provider from Google Play Services instead. // https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mListener); Log.d("BoundLocationMgr", "Listener added"); // Force an update with the last location, if available. Location lastLocation = mLocationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER); if (lastLocation != null) { mListener.onLocationChanged(lastLocation); } }
private void testLifecycle(LifecycleOwner owner) { Fragment fragment = (Fragment) owner; ActivityController<?> controller = startFragment(fragment); TestObserver<Lifecycle.Event> testObserver = AndroidLifecycle.createLifecycleProvider(owner).lifecycle().test(); controller.start(); controller.resume(); controller.pause(); controller.stop(); controller.destroy(); testObserver.assertValues( Lifecycle.Event.ON_CREATE, Lifecycle.Event.ON_START, Lifecycle.Event.ON_RESUME, Lifecycle.Event.ON_PAUSE, Lifecycle.Event.ON_STOP, Lifecycle.Event.ON_DESTROY ); }
private MethodSpec defineLifecycleHook() { final String methodName = "onLifecycleEvent"; Lifecycle.Event lifecycleEvent = annotatedElement.getAnnotation(LifecycleAware.class).value(); AnnotationSpec archLifeCycleSpec = AnnotationSpec.builder(OnLifecycleEvent.class) .addMember(ANNOT_DEFAULT_NAME, "$T.$L", Lifecycle.Event.class, lifecycleEvent) .build(); return MethodSpec.methodBuilder(lifecycleEvent.name()) .addAnnotation(archLifeCycleSpec) .addModifiers(Modifier.PUBLIC) .addStatement("$L.$L($T.$L)", FIELD_OBSERVER, methodName, Lifecycle.Event.class, lifecycleEvent) .build(); }
private void testBindUntilEvent(LifecycleOwner owner) { Fragment fragment = (Fragment) owner; ActivityController<?> controller = startFragment(fragment); TestObserver<Object> testObserver = observable.compose(AndroidLifecycle.createLifecycleProvider(owner).bindUntilEvent(Lifecycle.Event.ON_STOP)).test(); testObserver.assertNotComplete(); controller.start(); testObserver.assertNotComplete(); controller.resume(); testObserver.assertNotComplete(); controller.pause(); testObserver.assertNotComplete(); controller.stop(); testObserver.assertComplete(); }
@Override public boolean test(final T object) throws Exception { // We've already removed the reference, don't emit anymore items. if (lifecycleOwner == null) { return false; } boolean isDestroyed = lifecycleOwner.getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED; if (isDestroyed) { // This should have been handled in handleLifecycleEvent() at this point, but just being safe to not have // memory leaks. lifecycleOwner = null; } // If not destroyed, predicate is true and emits streams items as normal. Otherwise it ends. return !isDestroyed; }
/** * Decides whether the stream needs to be destroyed or subscribed to. */ private void handleCurrentLifecycleState() { if (lifecycleOwner != null && lifecycleOwner.getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED) { // No memory leaks please this.lifecycleOwner.getLifecycle().removeObserver(this); this.lifecycleOwner = null; this.baseReactiveType = null; } else if (LifecycleUtil.isInActiveState(lifecycleOwner) && !subscribed && baseReactiveType != null) { // Subscribe to stream with observer since the LifecycleOwner is now active but wasn't previously baseReactiveType.subscribeWithObserver(); subscribed = true; } }
@Test public void viewsAreCalledBeforeLifecycleIsReadyWithoutLifecycleAwareRx() throws Exception { // Lifecycle is "active" once it is STARTED, it's not ready yet at INITIALIZED or CREATED. lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); Observable.interval(1, TimeUnit.MILLISECONDS) .subscribeWith(new DisposableObserver<Long>() { @Override public void onNext(final Long value) { LifecycleTest.this.methodOnViewCalled = true; } @Override public void onError(final Throwable e) { } @Override public void onComplete() { } }); // Need to wait to give it time to potentially fail TimeUnit.MILLISECONDS.sleep(100); assertEquals(true, methodOnViewCalled); }
@Override public Lifecycle.Event apply(Lifecycle.Event lastEvent) throws Exception { switch (lastEvent) { case ON_CREATE: return Lifecycle.Event.ON_DESTROY; case ON_START: return Lifecycle.Event.ON_STOP; case ON_RESUME: return Lifecycle.Event.ON_PAUSE; case ON_PAUSE: return Lifecycle.Event.ON_STOP; case ON_STOP: return Lifecycle.Event.ON_DESTROY; case ON_DESTROY: throw new OutsideLifecycleException("Cannot bind to Activity lifecycle when outside of it."); default: throw new UnsupportedOperationException("Binding to " + lastEvent + " not yet implemented"); } }
/** * Required to place inside your activities {@code onStart} method. You'll also most likely want * to check that this Location Layer plugin instance inside your activity is null or not. * * @since 0.1.0 */ @RequiresPermission(anyOf = {ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}) @OnLifecycleEvent(Lifecycle.Event.ON_START) public void onStart() { if (locationLayerMode != LocationLayerMode.NONE) { setLocationLayerEnabled(locationLayerMode); } if (!compassManager.getCompassListeners().isEmpty() || (locationLayerMode == LocationLayerMode.COMPASS && compassManager.isSensorAvailable())) { compassManager.onStart(); } if (mapboxMap != null) { mapboxMap.addOnCameraMoveListener(this); } }
@Test public void testBindUntilLifecycleEvent() { BehaviorSubject<Lifecycle.Event> lifecycle = BehaviorSubject.create(); TestObserver<Object> testObserver = observable.compose(RxLifecycle.bindUntilEvent(lifecycle, Lifecycle.Event.ON_STOP)).test(); lifecycle.onNext(Lifecycle.Event.ON_CREATE); testObserver.assertNotComplete(); lifecycle.onNext(Lifecycle.Event.ON_START); testObserver.assertNotComplete(); lifecycle.onNext(Lifecycle.Event.ON_RESUME); testObserver.assertNotComplete(); lifecycle.onNext(Lifecycle.Event.ON_PAUSE); testObserver.assertNotComplete(); lifecycle.onNext(Lifecycle.Event.ON_STOP); testObserver.assertComplete(); }
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void downloadFont() { Log.d(Tags.viewmodel.name(), "downloadFont: Running"); String query = "name=Open Sans&weight=800&italic=0"; FontRequest fontRequest = new FontRequest( "com.google.android.gms.fonts", "com.google.android.gms", query, R.array.com_google_android_gms_fonts_certs); FontsContractCompat.FontRequestCallback fontCallback = new FontsContractCompat.FontRequestCallback() { @Override public void onTypefaceRetrieved(Typeface typeface) { // If we got our font apply it to the toolbar styleToolbar(typeface); } @Override public void onTypefaceRequestFailed(int reason) { Log.w(Tags.viewmodel.name(), "Failed to fetch Toolbar font: " + reason); } }; // Start async fetch on the handler thread FontsContractCompat.requestFont( mContext, fontRequest, fontCallback, getFontHandlerThread()); }
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void onCreate() { if (locationEngine.getValue() != null) { locationEngine.getValue().addLocationEngineListener(this); locationEngine.getValue().activate(); } }
@OnLifecycleEvent(Lifecycle.Event.ON_STOP) void stop() { if (alertDialog != null) { alertDialog.dismiss(); } }
@OnLifecycleEvent(Lifecycle.Event.ON_START) void start() { if (!isRegistered) { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); context.registerReceiver(internetConnectivityChangeBroadcastReceiver, intentFilter); isRegistered = true; } }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLifecycleRegistry = new LifecycleRegistry(this); mLifecycleRegistry.markState(Lifecycle.State.CREATED); navigator = NavigatorFactory.getInstance(); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); restoreViewStateFromBundle(savedInstanceState); initialize(); setupUI(savedInstanceState == null); }
@Override protected void onStart() { super.onStart(); mLifecycleRegistry.markState(Lifecycle.State.STARTED); LiveDataReactiveStreams.fromPublisher(viewModel.uiModels(viewState)) .observe(this, new UIObserver<>(this, errorMessageFactory())); viewModel.processEvents(events()); }
/** * 只有当 {@code mRootView} 不为 null, 并且 {@code mRootView} 实现了 {@link LifecycleOwner} 时, 此方法才会被调用 * 所以当您想在 {@link Service} 以及一些自定义 {@link View} 或自定义类中使用 {@code Presenter} 时 * 您也将不能继续使用 {@link OnLifecycleEvent} 绑定生命周期 * * @param owner link {@link SupportActivity} and {@link Fragment} */ @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void onDestroy(LifecycleOwner owner) { /** * 注意, 如果在这里调用了 {@link #onDestroy()} 方法, 会出现某些地方引用 {@code mModel} 或 {@code mRootView} 为 null 的情况 * 比如在 {@link RxLifecycle} 终止 {@link Observable} 时, 在 {@link io.reactivex.Observable#doFinally(Action)} 中却引用了 {@code mRootView} 做一些释放资源的操作, 此时会空指针 * 或者如果你声明了多个 @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) 时在其他 @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) * 中引用了 {@code mModel} 或 {@code mRootView} 也可能会出现此情况 */ owner.getLifecycle().removeObserver(this); }
private MethodSpec defineWrapperHook() { final String methodName = "onLifecycleEvent"; final String eventParam = "event"; String annotatedMethod = annotatedElement.getAnnotation(LifecycleAware.class).method(); return MethodSpec.methodBuilder(methodName) .addAnnotation(Override.class) .addParameter(Lifecycle.Event.class, eventParam) .addModifiers(Modifier.PUBLIC) .addCode(warningComment()) .addStatement("this.$L.$L()", FIELD_NAME, annotatedMethod) .build(); }
public void updateText(String msg) { if (lifecycle.getCurrentState().equals(Lifecycle.State.RESUMED)) { Log.d(TAG, "updateText: ON_RESUME"); } else { Log.d(TAG, "updateText: not resume!"); } }
@Test public void viewsAreNotCalledWhenLifecycleDestroyedWithSingle() throws Exception { Single.just("test") .compose(LifecycleBinder.bind(lifecycleOwner, new DisposableSingleObserver<String>() { @Override public void onSuccess(final String value) { LifecycleTest.this.methodOnViewCalled = true; } @Override public void onError(final Throwable e) { LifecycleTest.this.onErrorCalled = true; } })); lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_START); TimeUnit.MILLISECONDS.sleep(100); assertEquals(true, methodOnViewCalled); lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY); methodOnViewCalled = false; // Make sure there's a fresh state just as LifecycleOwner hits destroy onErrorCalled = false; // Need to wait to give it time to potentially fail TimeUnit.MILLISECONDS.sleep(100); assertEquals(false, methodOnViewCalled); assertEquals(false, onErrorCalled); }
@Test public void viewsAreNotCalledWhenLifecycleDestroyedWithMaybe() throws Exception { Maybe.just("test") .compose(LifecycleBinder.bind(lifecycleOwner, new DisposableMaybeObserver<String>() { @Override public void onSuccess(final String value) { LifecycleTest.this.methodOnViewCalled = true; } @Override public void onError(final Throwable e) { LifecycleTest.this.onErrorCalled = true; } @Override public void onComplete() { LifecycleTest.this.onCompleteCalled = true; } })); lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_START); TimeUnit.MILLISECONDS.sleep(100); assertEquals(true, methodOnViewCalled); lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY); methodOnViewCalled = false; // Make sure there's a fresh state just as LifecycleOwner hits destroy onCompleteCalled = false; onErrorCalled = false; // Need to wait to give it time to potentially fail TimeUnit.MILLISECONDS.sleep(100); assertEquals(false, methodOnViewCalled); assertEquals(false, onCompleteCalled); assertEquals(false, onErrorCalled); }
/** * Delaying stream subscription until the LifecycleOwner is ready. */ @Test public void viewsAreOnlyCalledWhenLifecycleActiveWithObservable() throws Exception { Observable.interval(1, TimeUnit.MILLISECONDS) .take(10) .compose(LifecycleBinder.bind(lifecycleOwner, new DisposableObserver() { @Override public void onNext(final Object value) { LifecycleTest.this.methodOnViewCalledCounter++; } @Override public void onError(final Throwable e) { } @Override public void onComplete() { } })); // Need to wait to give it time to potentially fail TimeUnit.MILLISECONDS.sleep(100); assertEquals(0, methodOnViewCalledCounter); lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); TimeUnit.MILLISECONDS.sleep(100); assertEquals(0, methodOnViewCalledCounter); lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_START); TimeUnit.MILLISECONDS.sleep(100); // At this point the views should now be called since the lifecycle is active assertEquals(10, methodOnViewCalledCounter); }
@Test public void testEndsImmediatelyOutsideLifecycle() { BehaviorSubject<Lifecycle.Event> lifecycle = BehaviorSubject.create(); lifecycle.onNext(Lifecycle.Event.ON_DESTROY); TestObserver<Object> testObserver = observable.compose(RxLifecycleAndroidLifecycle.bindLifecycle(lifecycle)).test(); testObserver.assertComplete(); }
@OnLifecycleEvent(Lifecycle.Event.ON_STOP) void stop() { if (isRegistered) { context.unregisterReceiver(internetConnectivityChangeBroadcastReceiver); isRegistered = false; } }
@Test public void onlyLastItemEmittedOnceLifecycleActiveWithObservable() throws Exception { final Long[] lastValue = {-1L}; Observable.interval(1, TimeUnit.MILLISECONDS) .take(10) .takeLast(1) .compose(LifecycleBinder.bind(lifecycleOwner, new DisposableObserver<Long>() { @Override public void onNext(final Long value) { LifecycleTest.this.methodOnViewCalledCounter++; lastValue[0] = value; } @Override public void onError(final Throwable e) { } @Override public void onComplete() { } })); // Need to wait to give it time to potentially fail TimeUnit.MILLISECONDS.sleep(100); assertEquals(0, methodOnViewCalledCounter); lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); TimeUnit.MILLISECONDS.sleep(100); assertEquals(0, methodOnViewCalledCounter); lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_START); TimeUnit.MILLISECONDS.sleep(100); // At this point the views should now be called since the lifecycle is active assertEquals(1, methodOnViewCalledCounter); // Make sure it's the last item emitted, not the first assertEquals(9L, lastValue[0].longValue()); }
private LifecycleRegistry init() { LifecycleRegistry registry = new LifecycleRegistry(this); registry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); registry.handleLifecycleEvent(Lifecycle.Event.ON_START); registry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); return registry; }
protected final void doFirstLoad(Runnable load) { Single.<Runnable>create(emitter -> { emitter.onSuccess(load); }) .zipWith( mCanFirstLoad.filter(bool -> bool).firstOrError(), (runnable, bool) -> runnable) .to(AutoDispose.with(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)).forSingle()) .subscribe(runnable -> { runnable.run(); }); }
public Observable<Lifecycle.Event> onResume() { return onEvent().filter(new Predicate<Lifecycle.Event>() { @Override public boolean test(@NonNull Lifecycle.Event event) throws Exception { return ON_RESUME.equals(event); } }); }
public Observable<Lifecycle.Event> onPause() { return onEvent().filter(new Predicate<Lifecycle.Event>() { @Override public boolean test(@NonNull Lifecycle.Event event) throws Exception { return ON_PAUSE.equals(event); } }); }
public Observable<Lifecycle.Event> onStop() { return onEvent().filter(new Predicate<Lifecycle.Event>() { @Override public boolean test(@NonNull Lifecycle.Event event) throws Exception { return ON_STOP.equals(event); } }); }
public Observable<Lifecycle.Event> onDestroy() { return onEvent().filter(new Predicate<Lifecycle.Event>() { @Override public boolean test(@NonNull Lifecycle.Event event) throws Exception { return ON_DESTROY.equals(event); } }); }
public Observable<Lifecycle.Event> onAny() { return onEvent().filter(new Predicate<Lifecycle.Event>() { @Override public boolean test(@NonNull Lifecycle.Event event) throws Exception { return ON_ANY.equals(event); } }); }
@Override public void onStart() { super.onStart(); mLifecycleRegistry.markState(Lifecycle.State.STARTED); LiveDataReactiveStreams.fromPublisher(viewModel.uiModels(viewState)) .observe(this, new UIObserver<>(this, errorMessageFactory())); viewModel.processEvents(events()); }
private void testBindToLifecycle(LifecycleOwner owner) { Fragment fragment = (Fragment) owner; LifecycleProvider<Lifecycle.Event> provider = AndroidLifecycle.createLifecycleProvider(owner); ActivityController<?> controller = startFragment(fragment); TestObserver<Object> createObserver = observable.compose(provider.bindToLifecycle()).test(); controller.start(); createObserver.assertNotComplete(); TestObserver<Object> startObserver = observable.compose(provider.bindToLifecycle()).test(); controller.resume(); createObserver.assertNotComplete(); startObserver.assertNotComplete(); TestObserver<Object> resumeObserver = observable.compose(provider.bindToLifecycle()).test(); controller.pause(); createObserver.assertNotComplete(); startObserver.assertNotComplete(); resumeObserver.assertComplete(); TestObserver<Object> pauseObserver = observable.compose(provider.bindToLifecycle()).test(); controller.stop(); createObserver.assertNotComplete(); startObserver.assertComplete(); pauseObserver.assertComplete(); TestObserver<Object> stopObserver = observable.compose(provider.bindToLifecycle()).test(); controller.destroy(); createObserver.assertComplete(); stopObserver.assertComplete(); }
boolean canRespond(){ if (lifecycleOwner == null){ return false; } Lifecycle lifecycle = lifecycleOwner.getLifecycle(); boolean isInitialized = lifecycle.getCurrentState().isAtLeast(Lifecycle.State.INITIALIZED); boolean isNotDestroyed = lifecycleState != LifecycleState.DESTROYED; return isInitialized && isNotDestroyed; }
boolean canRun(){ if (lifecycleOwner == null){ return false; } Lifecycle lifecycle = lifecycleOwner.getLifecycle(); boolean isInitialized = lifecycle.getCurrentState().isAtLeast(Lifecycle.State.INITIALIZED); boolean isNotDestroyed = lifecycleState != LifecycleState.DESTROYED; return isInitialized && isNotDestroyed; }
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) void removeLocationListener() { if (mLocationManager == null) { return; } mLocationManager.removeUpdates(mListener); mLocationManager = null; Log.d("BoundLocationMgr", "Listener removed"); }
@Override protected void onPause() { super.onPause(); mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE); }
@Override protected void onResume() { super.onResume(); mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); }