How to use LocalBroadcastManager?

后端 未结 13 3196
天命终不由人
天命终不由人 2020-11-21 04:15

How to use/locate LocalBroadcastManager as described in google docs and Service broadcast doc?

I tried to google it, but there is no code available to s

13条回答
  •  走了就别回头了
    2020-11-21 04:53

    localbroadcastmanager is deprecated, use implementations of the observable pattern instead.

    androidx.localbroadcastmanager is being deprecated in version 1.1.0

    Reason

    LocalBroadcastManager is an application-wide event bus and embraces layer violations in your app; any component may listen to events from any other component. It inherits unnecessary use-case limitations of system BroadcastManager; developers have to use Intent even though objects live in only one process and never leave it. For this same reason, it doesn’t follow feature-wise BroadcastManager .

    These add up to a confusing developer experience.

    Replacement

    You can replace usage of LocalBroadcastManager with other implementations of the observable pattern. Depending on your use case, suitable options may be LiveData or reactive streams.

    Advantage of LiveData

    You can extend a LiveData object using the singleton pattern to wrap system services so that they can be shared in your app. The LiveData object connects to the system service once, and then any observer that needs the resource can just watch the LiveData object.

     public class MyFragment extends Fragment {
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            LiveData myPriceListener = ...;
            myPriceListener.observe(this, price -> {
                // Update the UI.
            });
        }
    }
    

    The observe() method passes the fragment, which is an instance of LifecycleOwner, as the first argument. Doing so denotes that this observer is bound to the Lifecycle object associated with the owner, meaning:

    • If the Lifecycle object is not in an active state, then the observer isn't called even if the value changes.

    • After the Lifecycle object is destroyed, the observer is automatically removed

    The fact that LiveData objects are lifecycle-aware means that you can share them between multiple activities, fragments, and services.

提交回复
热议问题