Android Event bus talking about Eventbus

Source: Internet
Author: User
Tags eventbus

Eventbus Official documentation reads: Eventbus is a publish/subscribe the event bus optimized for Android.
This means that Eventbus is an efficient publish/SUBSCRIBE event bus mechanism under Android.

Eventbus can be used instead of traditional intent,handler,broadcast or interface functions to pass data between fragment,activity,service and threads, and execute methods.

Let's take a look at the official documentation about Eventbus:

    • Simplifies the communication between components
      • Decouples Event Senders and receivers
      • Performs well with activities, fragments, and background threads
      • Avoids complex and error-prone dependencies and life cycle issues
    • Makes your code simpler
    • is fast
    • Is tiny (~50k jar)
    • is proven in practice by apps with 100,000,000+ installs
    • Have advanced features like delivery threads, subscriber priorities, etc.

As you can see from the documentation, Eventbus has many advantages:

(1)简化组件间的通讯(2)事件发布者和订阅者解耦(3)在Activity、Fragment和子线程有优秀的执行能力(4)避免复杂和容易出错的依赖关系和生命周期问题(5)使你的代码更简单(EventBus采用了一种发布订阅设计模式(Publish/Subsribe),或称为观察者设计模式)(6)快(7)小(~ 50K的jar)(8)具有交付线程、用户优先级等高级功能

It says that Eventbus is an implementation of the observer pattern, which has the following three elements:

Event:事件(可以使任意类型对象)Subscriber:事件订阅者(接收特定的事件,onEvent、onEventMainThread、onEventBackgroundThread、onEventAsync)Publisher:事件发布者(可以通过post(Object)在任意线程任意位置发送事件)

From the official figure below, the schema of this observer pattern is intuitively illustrated:

1. Download Eventbus

GitHub Downloads:
Https://github.com/greenrobot/EventBus

Eventbus jar Download:
Https://github.com/greenrobot/EventBus/releases

Usage of 2.EventBus

(1) First introduce Eventbus
Eclipse: Add Eventbus.jar to the Libs, add to Build Path
Android Studio: Added in engineering gradle: Compile ' de.greenrobot:eventbus:3.0.0 '

(2) Define an event, define a class, inherit the default object, use to differentiate between events and transmit data, this example is msgevent (if there are more than one, you can define multiple msgevent).

(3) Adding subscribers and canceling subscriptions
Added subscribers: Eventbus.getdefault (). Register (this); The same class is used as the subscriber, and the framework obtains all the methods and their parameters through the reflection mechanism.
Unsubscribe: Eventbus.getdefault (). Unregister (this); When a subscriber is no longer in use or is closed, it is best to unsubscribe and no longer accept event messages.

The subscriber's class can define one or more of the following methods to receive the event:

// 与发布者在同一个线程public void onEvent(MsgEvent msg){}// 执行在主线程public void onEventMainThread(MsgEvent msg){}// 执行在子线程public void onEventBackgroundThread(MsgEvent msg){}// 执行在一个新的子线程public void onEventAsync(MsgEvent msg){}

(4) Publisher event: Eventbus.getdefault (). Post (new Msgevent ("Message 1 for mainline Cheng"));

一旦执行了此方法, 所有订阅者都会执行第二步定义的方法。

(5) Note: The Publisher post method parameter is the object type, which means that any event can be published. When a subscriber accepts a message, it can be executed as long as it defines either of the four methods of the second step, and the parameter and Publisher are published consistently. The publisher can also receive messages through the second step, and subscribers can also send messages to themselves as publishers.

A usage instance of 3.EventBus

Below we implement Eventbus instead of traditional handler to pass data between fragment;
This assumes that Afragment passes data to bfragment.

(1) Create event Msgevent

publicclass MsgEvent {    private String msg;    publicMsgEvent(String msg) {        super();        this.msg = msg;    }    publicgetMsg() {        return msg;    }}

(4) Add subscribers to Bfragment

 Public  class bfragment extends Fragment {    @Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);//interface creation, subscribe to events, accept messagesEventbus.getdefault (). Register ( This); }@Override     Public void OnDestroy() {Super. OnDestroy ();//Cancel the subscription when the interface is destroyedEventbus.getdefault (). Unregister ( This); }@Override     PublicViewOncreateview(Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View view = Inflater.inflate (R.layout.fragment_b,NULL);returnView }/** * The same thread as the publisher * @param MSG Event Msgevent */     Public void onEvent(Msgevent msg)    {String message = msg.getmsg (); }/** * Executes in the main thread, where you can set the data of the preempted directly to the interface * @param msg Event msgevent */     Public void Oneventmainthread(Msgevent msg)    {String message = msg.getmsg (); }/** * Executes on a child thread, if the publisher is a child thread then executes directly if the publisher is not a child thread, then creates a re-execution, where there may be a thread blocking problem * @param msg Event Msgevent * /     Public void Oneventbackgroundthread(Msgevent msg)    {String message = msg.getmsg (); }/** * Executes on a new child thread, applies to multiple thread task processing, internal wired pool management * @param msg Event msgevent */     Public void Oneventasync(Msgevent msg)    {String message = msg.getmsg (); }}

(3) Publisher post event (in afragment main thread)

EventBus.getDefault().post(new MsgEvent("主线程发的消息"));

Android Event bus talking about Eventbus

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.