About EventBus, from use to parse (a)

This article mainly on the use on EventBus, the next article will explain in detail the principles according to which the use of EventBus. Although RxJava EventBus can also function to achieve, but the principle is the same thing.

A, EventBus Profile

Is a side EventBus Android optimized publish / subscribe message bus, simplifies the inter-application communication components between the component and the background thread.

As a message bus has three main components:

Event (Event): can be any type of object. The event passed by the publisher of the event.

Event subscribers (Subscriber): receive a specific event.

Event Publisher (Publisher): used to notify the Subscriber an event occurs. In any event can be sent anywhere in the thread.

The figure probably explains the workflow of the entire EventBus: publisher events (Publisher) event (Event) method is sent by post (). EventBus internal processing, find subscribed to the event (Event) event subscriber (Subscriber). Then the event subscriber (for Subscriber) performs the correlation process by the onEvent () method receives events (on the onEvent () with changes in the EventBus 3.0, described in detail below).

Second, the simple use of EventBus

1, the project to rely EventBus

Add a reference build.gradle

 compile 'de.greenrobot:eventbus:3.0.0-beta1'

2, tectonic event (Event) objects. That is to send a message class
for each message type, the corresponding type of event. Here we define two classes messaging. Back to explain the specific role.

public class NewsEvent {
    private String message;

    public NewsEvent(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

public class ToastEvent {
    private String content;

    public ToastEvent(String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

3, registration / release event subscription (Subscriber)

EventBus.getDefault().register(this);//注册事件 其中this代表订阅者

What specific registered subscription to the event, the need onEvent () method to illustrate. Before EventBus 3.0, onEvent () method is used to receive a specified event (Event) type of the object, and then correlating process operation. After EventBus 3.0, onEvent () method can customize the method name, but to add comments @Subscribe.

@Subscribe
   public void onToastEvent(ToastEvent event){
       Toast.makeText(MainActivity.this,event.getContent(),Toast.LENGTH_SHORT).show();
   }

By register (this) to indicate that the subscriber has subscribed, indicates that the specified subscription to an event ToastEvent by onToastEvent (ToastEvent event). Subscribe here is complete.

Note that: the general register subscribe onCreate () method. In onDestory () method will be unsubscribe.

@Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

4, sending a message
subscription has been completed, then it can be sent to subscribe.

EventBus.getDefault().post(new ToastEvent("Toast,发个提示,祝大家新年快乐!"));

So onToastEvent (ToastEvent event) will receive events, and pop-up prompts.

EventBus the basis of the use of the process is one such.

In fact, EventBus there are a lot of other functions. Here we introduce one by one.

Three, EventBus advanced use

1. Thread mode ThreadMode

After the event you received, if in a non-UI thread, you have to update the UI how to do? If you are in the UI thread, you have to perform time-consuming operation, how do? Otherwise, and so on, all by ThreadMode help you solve.

Usage show:

@Subscribe(threadMode = ThreadMode.MainThread)
    public void  onNewsEvent(NewsEvent event){
        String message = event.getMessage();
        mTv_message.setText(message);
    }

It is simple to use, through a @Subscribe(threadMode = ThreadMode.MainThread)designated can.
The following detailed description under ThreadMode.

About ThreadMode, a total of four models PostThread, PostThread, BackgroundThread and Async.

** PostThread: ** handling events in and send events in the same process, so the event processing time should not be too long, otherwise affect the sending thread events.

** MainThread: ** event processing is executed in the UI thread. Event Processing time not too long, this goes without saying, it will be a long ANR's.

** BackgroundThread: ** If the event is released out of the UI thread, the event handler will run in the sub-thread, if the event was originally released out of the child thread, then the event processing executed directly in the child thread. All pending events will be added to a queue, by a corresponding thread in order to deal with these events, if an event is taking too long, clog distribute or handling the incident behind.

** Async: ** Event processing is executed in a separate thread, is mainly used to perform time-consuming operations in a background thread, each event will open a thread.

2.priority event priority

The higher the priority of similar broadcast event priority, the priority of preferential access to the message.
Usage show:

@Subscribe(priority = 100)
    public void onToastEvent(ToastEvent event){
        Toast.makeText(MainActivity.this,event.getContent(),Toast.LENGTH_SHORT).show();
    }

When a plurality of subscribers (for Subscriber) subscribe to the same event type, event type consistent i.e. corresponding to the processing method received, the high priority (priority value larger set), it will first receive event processing ; low priority (priority value set smaller), for treatment will receive event.

In addition, EventBus may also terminate the function of the event to pass on.
Usage show:

 @Subscribe(priority = 100)
    public void onToastEvent(ToastEvent event){
        Toast.makeText(MainActivity.this,event.getContent(),Toast.LENGTH_SHORT).show();
        EventBus.getDefault().cancelEventDelivery(event);
    }

So that other lower priority than the 100, and subscribed to the event subscribers will not receive the event.

3.EventBus viscous event

EventBus addition to general event is also supported viscous event. It can be understood as: subscription after the release event, but also receive event. Subscribe / unsubscribe and ordinary events, but the method is different subscription process, add sticky = true needs annotations.
Usage show:

@Subscribe(priority = 100,sticky = true)
    public void onToastEvent(ToastEvent event){
        Toast.makeText(MainActivity.this,event.getContent(),Toast.LENGTH_SHORT).show();
        EventBus.getDefault().cancelEventDelivery(event);
    }

Thus, assuming a ToastEvent event has been released at this time has not yet registered subscription. When you set a sticky = true, after the release ToastEvent event, to register. Still be able to receive events before the release.

But this time, the way publishing events changed.

EventBus.getDefault().postSticky(new ToastEvent("Toast,发个提示,祝大家新年快乐!"));

If we no longer need the viscous event we can remove

EventBus.getDefault().removeStickyEvent(ToastEvent.class);

Remove all sticky or call events

EventBus.getDefault().removeAllStickyEvents();

4.EventBus Configuration

EventBus EventBuilder added in version 2.3 to configure each side of EventBus parties.

For example: how to build a EventBus remain silent when no subscribers when publishing event.

EventBus eventBus = EventBus.builder()
.logNoSubscriberMessages(false)
.sendNoSubscriberEvent(false)
.build();

With the above arrangement, when an event is not a subscriber, not output log information, and will not release a default information.

The default configuration EventBus instance, using EventBus.getDefault () is a simple method. Get a singleton instance of EventBus. EventBusBuilder installDefaultEventBus method also allows to configure the default EventBus instance.

Note: Data of different objects EventBus is not shared. EventBus by a target to publish the event, only by subscribing to the same EventBus object events to receive the event. So using the above EventBus.getDefault () obtained are the same instance.

It is engaged in the development of the Android engineers for seven years, a lot of people ask me privately, 2019 Android how advanced the science, there is no method?

Yes, at the beginning I spent more than a month to sort out learning materials, hoping to help those who want to enhance the advanced Android development, but do not know how advanced learning friends. [ Including advanced UI, performance optimization, Architect courses, NDK, Kotlin, hybrid development (ReactNative + Weex), Flutter and other technical information architecture ], hoping to help review your pre-interview and find a good job, but also save in time they search for information online to learn.

Obtaining: Add Android architecture exchange QQ group chat: 513 088 520, into the group that is to receive the information! ! !

Click on the link to join a group chat Android mobile architecture [total population]: join a group chat

Sourcebook

Guess you like

Origin blog.csdn.net/weixin_43351655/article/details/90813162