android.arch.lifecycle.LifecycleOwner Java Examples

The following examples show how to use android.arch.lifecycle.LifecycleOwner. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SingleLiveEvent.java    From Android-VMLib with Apache License 2.0 6 votes vote down vote up
@MainThread
@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull final Observer<T> observer) {
    if (single) {
        if (hasActiveObservers()) {
            L.d("Multiple observers registered but only one will be notified of changes.");
        }
        // Observe the internal MutableLiveData
        super.observe(owner, new Observer<T>() {
            @Override
            public void onChanged(@Nullable T t) {
                if (mPending.compareAndSet(true, false)) {
                    observer.onChanged(t);
                }
            }
        });
    } else {
        super.observe(owner, observer);
    }
}
 
Example #2
Source File: LiveEventBus.java    From LiveEventBus with Apache License 2.0 6 votes vote down vote up
@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
    SafeCastObserver<T> safeCastObserver = new SafeCastObserver<>(observer);
    //保存LifecycleOwner的当前状态
    Lifecycle lifecycle = owner.getLifecycle();
    Lifecycle.State currentState = lifecycle.getCurrentState();
    int observerSize = getLifecycleObserverMapSize(lifecycle);
    boolean needChangeState = currentState.isAtLeast(Lifecycle.State.STARTED);
    if (needChangeState) {
        //把LifecycleOwner的状态改为INITIALIZED
        setLifecycleState(lifecycle, Lifecycle.State.INITIALIZED);
        //set observerSize to -1,否则super.observe(owner, observer)的时候会无限循环
        setLifecycleObserverMapSize(lifecycle, -1);
    }
    super.observe(owner, safeCastObserver);
    if (needChangeState) {
        //重置LifecycleOwner的状态
        setLifecycleState(lifecycle, currentState);
        //重置observer size,因为又添加了一个observer,所以数量+1
        setLifecycleObserverMapSize(lifecycle, observerSize + 1);
        //把Observer置为active
        hookObserverActive(safeCastObserver, true);
    }
    //更改Observer的version
    hookObserverVersion(safeCastObserver);
}
 
Example #3
Source File: ActivityCompatibilityUtility.java    From scene with Apache License 2.0 6 votes vote down vote up
@MainThread
public static void addConfigurationChangedListener(@NonNull final Activity activity, @NonNull final LifecycleOwner lifecycleOwner,
                                                   @NonNull final ConfigurationChangedListener configurationChangedListener) {
    ThreadUtility.checkUIThread();
    if (isDestroyed(activity, lifecycleOwner)) {
        return;
    }
    final SceneActivityCompatibilityLayerFragment fragment = install(activity);
    if (fragment.isAdded()) {
        fragment.addConfigurationChangedListener(lifecycleOwner, configurationChangedListener);
    } else {
        fragment.addOnActivityCreatedCallback(new SceneActivityCompatibilityLayerFragment.OnActivityCreatedCallback() {
            @Override
            public void onActivityCreated() {
                fragment.removeOnActivityCreatedCallback(this);
                if (isDestroyed(activity, lifecycleOwner)) {
                    return;
                }
                fragment.addConfigurationChangedListener(lifecycleOwner, configurationChangedListener);
            }
        });
    }
}
 
Example #4
Source File: ActivityCompatibilityUtility.java    From scene with Apache License 2.0 6 votes vote down vote up
@MainThread
@RequiresApi(Build.VERSION_CODES.M)
public static void requestPermissions(@NonNull final Activity activity, @NonNull final LifecycleOwner lifecycleOwner,
                                      @NonNull final String[] permissions, final int requestCode,
                                      @NonNull final PermissionResultCallback resultCallback) {
    ThreadUtility.checkUIThread();
    if (isDestroyed(activity, lifecycleOwner)) {
        return;
    }
    final SceneActivityCompatibilityLayerFragment fragment = install(activity);
    if (fragment.isAdded()) {
        fragment.requestPermissionsByScene(lifecycleOwner, permissions, requestCode, resultCallback);
    } else {
        fragment.addOnActivityCreatedCallback(new SceneActivityCompatibilityLayerFragment.OnActivityCreatedCallback() {
            @Override
            public void onActivityCreated() {
                fragment.removeOnActivityCreatedCallback(this);
                if (isDestroyed(activity, lifecycleOwner)) {
                    return;
                }
                fragment.requestPermissionsByScene(lifecycleOwner, permissions, requestCode, resultCallback);
            }
        });
    }
}
 
Example #5
Source File: ActivityCompatibilityUtility.java    From scene with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@MainThread
public static void startActivityForResult(@NonNull final Activity activity, @NonNull final LifecycleOwner lifecycleOwner,
                                          @NonNull final Intent intent, final int requestCode,
                                          @Nullable final Bundle options,
                                          @NonNull final ActivityResultCallback resultCallback) {
    ThreadUtility.checkUIThread();
    if (isDestroyed(activity, lifecycleOwner)) {
        return;
    }
    final SceneActivityCompatibilityLayerFragment fragment = install(activity);
    if (fragment.isAdded()) {
        fragment.startActivityForResultByScene(lifecycleOwner, intent, requestCode, options, resultCallback);
    } else {
        fragment.addOnActivityCreatedCallback(new SceneActivityCompatibilityLayerFragment.OnActivityCreatedCallback() {
            @Override
            public void onActivityCreated() {
                fragment.removeOnActivityCreatedCallback(this);
                if (isDestroyed(activity, lifecycleOwner)) {
                    return;
                }
                fragment.startActivityForResultByScene(lifecycleOwner, intent, requestCode, options, resultCallback);
            }
        });
    }
}
 
Example #6
Source File: ActivityCompatibilityUtility.java    From scene with Apache License 2.0 6 votes vote down vote up
@MainThread
public static void startActivityForResult(@NonNull final Activity activity, @NonNull final LifecycleOwner lifecycleOwner,
                                          @NonNull final Intent intent, final int requestCode,
                                          @NonNull final ActivityResultCallback resultCallback) {
    ThreadUtility.checkUIThread();
    if (isDestroyed(activity, lifecycleOwner)) {
        return;
    }
    final SceneActivityCompatibilityLayerFragment fragment = install(activity);
    if (fragment.isAdded()) {
        fragment.startActivityForResultByScene(lifecycleOwner, intent, requestCode, resultCallback);
    } else {
        fragment.addOnActivityCreatedCallback(new SceneActivityCompatibilityLayerFragment.OnActivityCreatedCallback() {
            @Override
            public void onActivityCreated() {
                fragment.removeOnActivityCreatedCallback(this);
                if (isDestroyed(activity, lifecycleOwner)) {
                    return;
                }
                fragment.startActivityForResultByScene(lifecycleOwner, intent, requestCode, resultCallback);
            }
        });
    }
}
 
Example #7
Source File: GasSliderView.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
public GasSliderView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
    startGasLimit = BigInteger.valueOf(C.GAS_LIMIT_DEFAULT);

    calculateStaticScaleFactor();

    /*
    Below code will attache current view with activity/fragment lifecycle
     */
    ((LifecycleOwner)context).getLifecycle().addObserver(this);

    inflate(context, R.layout.item_gas_slider, this);

    bindViews();
}
 
Example #8
Source File: SingleLiveEvent.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
@MainThread
public void observe(LifecycleOwner owner, final Observer<T> observer) {

    if (hasActiveObservers()) {
        Log.w(TAG, "Multiple observers registered but only one will be notified of changes.");
    }

    // Observe the internal MutableLiveData
    super.observe(owner, new Observer<T>() {
        @Override
        public void onChanged(@Nullable T t) {
            if (mPending.compareAndSet(true, false)) {
                observer.onChanged(t);
            }
        }
    });
}
 
Example #9
Source File: SceneActivityCompatibilityLayerFragment.java    From scene with Apache License 2.0 6 votes vote down vote up
@MainThread
@RequiresApi(Build.VERSION_CODES.M)
void requestPermissionsByScene(@NonNull final LifecycleOwner lifecycleOwner, @NonNull String[] permissions,
                               final int requestCode, @NonNull final PermissionResultCallback resultCallback) {
    if (!isCurrentStatusValid(lifecycleOwner)) {
        return;
    }
    mPermissionResultCallbackMap.put(requestCode, resultCallback);
    requestPermissions(permissions, requestCode);
    lifecycleOwner.getLifecycle().addObserver(new LifecycleObserver() {
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        void onDestroy() {
            lifecycleOwner.getLifecycle().removeObserver(this);
            mPermissionResultCallbackMap.remove(requestCode);
        }
    });
}
 
Example #10
Source File: SceneActivityCompatibilityLayerFragment.java    From scene with Apache License 2.0 6 votes vote down vote up
@MainThread
void startActivityForResultByScene(@NonNull final LifecycleOwner lifecycleOwner, @NonNull Intent intent,
                                   final int requestCode, @NonNull ActivityResultCallback resultCallback) {
    if (!isCurrentStatusValid(lifecycleOwner)) {
        return;
    }

    if (requestCode < 0) {
        startActivity(intent);
        return;
    }
    mResultCallbackMap.put(requestCode, resultCallback);
    startActivityForResult(intent, requestCode);
    lifecycleOwner.getLifecycle().addObserver(new LifecycleObserver() {
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        void onDestroy() {
            lifecycleOwner.getLifecycle().removeObserver(this);
            mResultCallbackMap.remove(requestCode);
        }
    });
}
 
Example #11
Source File: LiveEvent.java    From LiveEventBus with Apache License 2.0 6 votes vote down vote up
@MainThread
public void observeSticky(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
    if (owner.getLifecycle().getCurrentState() == DESTROYED) {
        // ignore
        return;
    }
    LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
    ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
    if (existing != null && !existing.isAttachedTo(owner)) {
        throw new IllegalArgumentException("Cannot add the same observer"
                + " with different lifecycles");
    }
    if (existing != null) {
        return;
    }
    owner.getLifecycle().addObserver(wrapper);
}
 
Example #12
Source File: NavigationScene.java    From scene with Apache License 2.0 6 votes vote down vote up
@MainThread
public void addNavigationListener(@NonNull final LifecycleOwner lifecycleOwner, @NonNull final NavigationListener listener) {
    ThreadUtility.checkUIThread();
    if (lifecycleOwner.getLifecycle().getCurrentState() == DESTROYED) {
        // ignore
        return;
    }
    this.mNavigationListenerList.add(listener);
    lifecycleOwner.getLifecycle().addObserver(new LifecycleObserver() {
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        void onDestroy() {
            lifecycleOwner.getLifecycle().removeObserver(this);
            mNavigationListenerList.remove(listener);
        }
    });
}
 
Example #13
Source File: VideoCardPresenter.java    From leanback-showcase with Apache License 2.0 6 votes vote down vote up
CardViewHolder(ImageCardView view, Context context) {
    super(view);
    mContext = context;
    Context wrapper = new ContextThemeWrapper(mContext, R.style.MyPopupMenu);
    mPopupMenu = new PopupMenu(wrapper, view);
    mPopupMenu.inflate(R.menu.popup_menu);

    mPopupMenu.setOnMenuItemClickListener(this);
    view.setOnLongClickListener(this);

    mOwner = (LifecycleOwner) mContext;

    mDefaultBackground = mContext.getResources().getDrawable(R.drawable.no_cache_no_internet, null);
    mDefaultPlaceHolder = new RequestOptions().
            placeholder(mDefaultBackground);

    mCardView = (ImageCardView) CardViewHolder.this.view;
    Resources resources = mCardView.getContext().getResources();
    mCardView.setMainImageDimensions(Math.round(
            resources.getDimensionPixelSize(R.dimen.card_width)),
            resources.getDimensionPixelSize(R.dimen.card_height));

    mFragmentActivity = (FragmentActivity) context;
    mViewModel = ViewModelProviders.of(mFragmentActivity).get(VideosViewModel.class);
}
 
Example #14
Source File: RtmpPublisher.java    From RtmpPublisher with Apache License 2.0 6 votes vote down vote up
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause(LifecycleOwner owner) {
    if (camera != null) {
        camera.close();
    }
    glView.onPause();
    glView.queueEvent(new Runnable() {
        @Override
        public void run() {
            renderer.pause();
        }
    });
    if (streamer.isStreaming()) {
        streamer.stopStreaming();
    }
}
 
Example #15
Source File: SnackbarMessage.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
public void observe(LifecycleOwner owner, final SnackbarObserver observer) {
    super.observe(owner, new Observer<Integer>() {
        @Override
        public void onChanged(@Nullable Integer t) {
            if (t == null) {
                return;
            }
            observer.onNewMessage(t);
        }
    });
}
 
Example #16
Source File: SceneActivityCompatibilityLayerFragment.java    From scene with Apache License 2.0 5 votes vote down vote up
private boolean isCurrentStatusValid(@NonNull final LifecycleOwner lifecycleOwner) {
    ThreadUtility.checkUIThread();
    Activity activity = getActivity();
    if (!Utility.isActivityStatusValid(activity)) {
        return false;
    }

    if (lifecycleOwner.getLifecycle().getCurrentState() == DESTROYED) {
        // ignore
        return false;
    }
    return true;
}
 
Example #17
Source File: SceneActivityCompatibilityLayerFragment.java    From scene with Apache License 2.0 5 votes vote down vote up
@MainThread
void addConfigurationChangedListener(@NonNull final LifecycleOwner lifecycleOwner,
                                     @NonNull final ConfigurationChangedListener configurationChangedListener) {
    if (!isCurrentStatusValid(lifecycleOwner)) {
        return;
    }
    mConfigurationChangedListenerList.add(configurationChangedListener);
    lifecycleOwner.getLifecycle().addObserver(new LifecycleObserver() {
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        void onDestroy() {
            lifecycleOwner.getLifecycle().removeObserver(this);
            mConfigurationChangedListenerList.remove(configurationChangedListener);
        }
    });
}
 
Example #18
Source File: UserProfileBaseViewModel.java    From budgetto with MIT License 5 votes vote down vote up
public void observe(LifecycleOwner owner, FirebaseObserver<FirebaseElement<User>> observer) {
    if(liveData.getValue() != null) observer.onChanged(liveData.getValue());
    liveData.observe(owner, new Observer<FirebaseElement<User>>() {
        @Override
        public void onChanged(@Nullable FirebaseElement<User> firebaseElement) {
            if(firebaseElement != null) observer.onChanged(firebaseElement);

        }
    });
}
 
Example #19
Source File: WalletEntryBaseViewModel.java    From budgetto with MIT License 5 votes vote down vote up
public void observe(LifecycleOwner owner, FirebaseObserver<FirebaseElement<WalletEntry>> observer) {
    if(liveData.getValue() != null) observer.onChanged(liveData.getValue());
    liveData.observe(owner, new Observer<FirebaseElement<WalletEntry>>() {
        @Override
        public void onChanged(@Nullable FirebaseElement<WalletEntry> element) {
            if(element != null) observer.onChanged(element);
        }
    });
}
 
Example #20
Source File: SingleLiveEvent.java    From Word-Search-Game with GNU General Public License v3.0 5 votes vote down vote up
@MainThread
@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
    super.observe(owner, t -> {
        if (mPending.compareAndSet(true, false)) {
            observer.onChanged(t);
        }
    });
}
 
Example #21
Source File: NavigationSceneManager.java    From scene with Apache License 2.0 5 votes vote down vote up
public void removeOnBackPressedListener(@NonNull OnBackPressedListener onBackPressedListener) {
    NonNullPair<LifecycleOwner, OnBackPressedListener> target = null;
    for (int i = mOnBackPressedListenerList.size() - 1; i >= 0; i--) {
        NonNullPair<LifecycleOwner, OnBackPressedListener> pair = mOnBackPressedListenerList.get(i);
        if (pair.second == onBackPressedListener) {
            target = pair;
            break;
        }
    }
    mOnBackPressedListenerList.remove(target);
}
 
Example #22
Source File: UserViewModel.java    From AndroidBlueprints with Apache License 2.0 5 votes vote down vote up
public void logout(LifecycleOwner owner) {
    if (user.getValue() != null) {
        repository.logout(user.getValue().data);
    }
    userIdentifier = null;
    user.removeObservers(owner);
    user = null;
}
 
Example #23
Source File: DataLoadTask.java    From DataLoader with Apache License 2.0 5 votes vote down vote up
@MainThread
void addListener(@NonNull LifecycleOwner owner, @NonNull final LoadListener<T> listener) {
    liveData.observe(owner, new Observer<T>() {
        @Override
        public void onChanged(@Nullable T t) {
            listener.onDataArrived(t);
        }
    });
}
 
Example #24
Source File: QuestionsPresenter.java    From mvp-android-arch-component with MIT License 5 votes vote down vote up
@Inject public QuestionsPresenter(QuestionRepository repository, QuestionsContract.View view,
    @RunOn(IO) Scheduler ioScheduler, @RunOn(UI) Scheduler uiScheduler) {
  this.repository = repository;
  this.view = view;
  this.ioScheduler = ioScheduler;
  this.uiScheduler = uiScheduler;

  // Initialize this presenter as a lifecycle-aware when a view is a lifecycle owner.
  if (view instanceof LifecycleOwner) {
    ((LifecycleOwner) view).getLifecycle().addObserver(this);
  }

  disposeBag = new CompositeDisposable();
}
 
Example #25
Source File: BasePresenter.java    From Aurora with Apache License 2.0 5 votes vote down vote up
/**
 * 只有当 {@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);
}
 
Example #26
Source File: LiveEventBusCore.java    From LiveEventBus with Apache License 2.0 5 votes vote down vote up
@MainThread
private void observeStickyInternal(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
    ObserverWrapper<T> observerWrapper = new ObserverWrapper<>(observer);
    liveData.observe(owner, observerWrapper);
    logger.log(Level.INFO, "observe sticky observer: " + observerWrapper + "(" + observer + ")"
            + " on owner: " + owner + " with key: " + key);
}
 
Example #27
Source File: LifecycleViewHolder.java    From NIM_Android_UIKit with MIT License 5 votes vote down vote up
public LifecycleViewHolder(ViewGroup parent, int layoutId, LifecycleOwner outerLifecycleOwner) {
    super(parent, layoutId);

    outerLifecycleOwner.getLifecycle().addObserver(new GenericLifecycleObserver() {
        @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            if (event == Lifecycle.Event.ON_DESTROY) {
                if (mLifecycle != null) {
                    mLifecycle.markState(Lifecycle.State.DESTROYED);
                }
            }
        }
    });
}
 
Example #28
Source File: SearchFragment.java    From leanback-showcase with Apache License 2.0 5 votes vote down vote up
private void subscribeNetwork() {
    NetworkLiveData.sync(this.getActivity())
            .observe((LifecycleOwner) this.getActivity(), new Observer<Boolean>() {
                @Override
                public void onChanged(@Nullable Boolean isNetworkAvailable) {
                    if (isNetworkAvailable) {
                        getActivity().findViewById(R.id.no_internet_search)
                                .setVisibility(View.GONE);
                    } else {
                        getActivity().findViewById(R.id.no_internet_search)
                                .setVisibility(View.VISIBLE);
                    }
                }
            });
}
 
Example #29
Source File: Presenter.java    From rxjava-RxLife with Apache License 2.0 5 votes vote down vote up
public Presenter(LifecycleOwner owner) {
    super(owner); //添加生命周期监听
    Observable.interval(1, 1, TimeUnit.SECONDS)
        .as(RxLife.as(this)) //这里的this 为Scope接口对象
        .subscribe(aLong -> {
            Log.e("LJX", "accept aLong=" + aLong);
        });
}
 
Example #30
Source File: TickerViewModel.java    From coursera-android with MIT License 4 votes vote down vote up
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
    // Not implemented
}