Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
903 views
in Technique[技术] by (71.8m points)

androidx - what is the replacement for lifeCycler-extensions

In a android library it is using

Implementation("androidx.lifecycle:lifecycle-extensions:2.2.0") {
        exclude group: "android.arch.lifecycle", module: "runtime"
    }

this is the usage:

// in library:
class AppLifecycleObserver implements LifecycleObserver {

    protected Context mAppContext;
    protected Callback mCb;

    AppLifecycleObserver(@NonNull Context appContext, @NonNull Callback cb) {
        mAppContext = appContext;
        mCb = cb;
    }

    public void register() {
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart() {
        mCb.doSomething();
    }
}

// in the app who uses this library will call the AppLifecycleObserver::register():
        mLifecycleObserver = new AppLifecycleObserver(context, callback);
        mLifecycleObserver.register();

question 1: it is said

The APIs in lifecycle-extensions have been deprecated. Instead, add dependencies for the specific Lifecycle artifacts you need.

what is the replacement for lifecycle-extensions?

question 2: lifecycle release note that Behavior Changes:

LifecycleRegistry now verifies that its methods are called on main thread. It was always a requirement for lifecycles of activities, fragments etc. An addition of observers from non-main threads resulted in hard to catch crashes in runtime. 

The ProcessLifecycleOwner.get().getLifecycle().addObserver(this) will cause rash if not running in main thread. How to allow the call in any thread but not crash (dont know how the library user app will make the call in what thread)? Note: we dont own a LifecycleRegistry here.

question from:https://stackoverflow.com/questions/65850618/what-is-the-replacement-for-lifecycler-extensions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

seems this works:

  1. lifecycle-process
  2. just check and make sure it runs in main thread:
if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
   Handler mainLoopHandler = new Handler(Looper.getMainLooper());
   Runnable myRunnable = new Runnable() {
            @Override
            public void run() {
                getLifeCycle().addObserver(AppLifecycleObserver.this);
            }
        };
        mainLoopHandler.post(myRunnable);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...