No poetic female program apologise not good cook ~ reprint please indicate the source, the From Li Shiyu – blog.csdn.net/cjm24848365…

Now when an interviewer asks you, “How do activities communicate with each other?”

The answer he wanted to hear wasn’t: Intent, Handler, EventBus, RxBus, broadcast.

All this was old and primitive, but what he wanted to hear was LiveDataBus!

Official recommendations from Google IO 2018: Use LivedataBus for communication between activities, activities and fragments, and fragments.

So what is LiveDataBus?

Why should it beat Handler, EventBus, RxBus?

What are its obvious advantages?

Don’t worry, let’s start with the simplest example:

Describe the above demo first.

There is a Button in the MainActivity, Button, and clicking Button will jump to the Bactivity.

When we arrive at Bactivity, we receive a message from MainActivity saying “Go for the interview!” .

And it comes out in the form of toast.

With that in mind, let’s take a look at how the code works.

[Code implementation]

① In MainActivity, when we click the button, we send a message:

public void click(View view) {
    // Send a message
    LiveDataBus.getInstance().with("msg", String.class).postValue("Hello, everyone!);
    Intent intent=new Intent(this,SecActivity.class);
    startActivity(intent);
}
Copy the code

② In the Bactivity, define an observer that receives data and displays it in the form of toast.

// Define an observer to receive data
LiveDataBus.getInstance().with("msg", String.class).observe(
        this.new Observer<String>() {
            @Override
            public void onChanged(String msg) {
                if(msg! =null){
                    Toast.makeText(SecActivity.this, msg, Toast.LENGTH_SHORT).show(); }}});Copy the code

③ Finally, let’s look at our minimalist version of LiveDataBus.

/** * This bus is used to pass data from any class directly to activities or fragments */
public class LiveDataBus {
    // Store subscribers
    private Map<String, MutableLiveData<Object>> bus;

    private static LiveDataBus liveDataBus = new LiveDataBus();

    private LiveDataBus(a) {
        bus = new HashMap<>();
    }

    public static LiveDataBus getInstance(a) {
        return liveDataBus;
    }

    // Register a subscriber, (save to map)
    public synchronized <T> MutableLiveData<T> with(String key, Class<T> type) {
        if(! bus.containsKey(key)) { bus.put(key,new MutableLiveData<Object>());
        }
        return(MutableLiveData<T>) bus.get(key); }}Copy the code

Okay, that’s all there is to it, doesn’t it feel easy?

【 Instructions 】

Diagram of sending messages:

  • When we want to send a message, we call the LIVEDatabus.getInstance ().with(API), set a key, set a value type (value can be any type), When we want to send a message, we call postValue() and put what we want to send into it.

  • Once emitted, anywhere else in the program (such as an Activity or Fragment) that also defines an observer and its key is “MSG”, that observer can receive the Value emitted in the postValue.

  • The observer we defined will have an onChanged() callback, and in onChanged() we will get the data sent from MainActivity.

[Analysis Principle]

Ok, now we can analyze how it is implemented.

A diagram of sorrow, or to draw a picture for you:

  • First, we design a LiveDataBus bus on which a lot of information is registered.

    The bus holds a hashMap that stores data in key-value form, key(String),value(MutableLiveData).

    And the bus is a singleton pattern.

  • When I send messages, the API we use is liveDatabus.getInstance ().with… When the message is sent, it registers the message in the HashMap with the corresponding key “MSG”.

  • Once the message is registered, let’s look at where it is used: it is used to unbind an observer.

    Use the same API liveDatabus.getInstance ().with… .

    The return value of this API is a MutableLiveData,

    So, in effect, it binds this observe to MutableLiveData.

Let’s see what MutableLiveData is.

MutableLiveData inherited from LiveData:

Let’s dive into the LiveData source and see the notice () method:

The above is our specific execution process analysis.

Now let’s make a summary ~

【 summary 】

LiveEventBus is an Android message bus, based on LiveData, with life cycle awareness, support Sticky, support AndroidX, support cross-process, support cross-app.

As to why it has life awareness, you can speak from the source point of view.

That is, it is actually the same thing as Glide’s awareness life cycle, with an empty Fragment created inside.

LiveDataBus compared with EventBus and RxBus

  • LiveDataBus vs. EventBus:

    The implementation of LiveDataBus is extremely simple. Compared to the complex implementation of EventBus, LiveDataBus requires only one class to implement

  • LiveDataBus vs. RxBus:

    LiveDataBus reduces the size of APK packages and relies better on support. Because LiveDataBus relies only on the official Android component, LiveData, it implements only one class. RxBus relies on RxJava and RxAndroid.

  • Finally, LiveDataBus has lifecycle awareness. Using callers on Android requires no de-registration, is more convenient than using EventBus and RxBus, and has no memory leak risk.

Accumulate drip, do yourself ~