Examples of Eventbus for Android

Source: Internet
Author: User

Brief introduction

Eventbus is a great event subscription with the release framework, project address: Https://github.com/greenrobot/EventBus.

Role

interface-based communication issues between the various components of Android:

1 increases the coupling between components, and the modification of one component may cause modifications to another component, so the flexibility is not high.
2 is full of code that is filled with boilerplate words:
Defining Interfaces and callbacks
Managing Listeners
Passing the call chain between tiers

In Android, the interaction between common components is as follows:

The following is a list/details scenario to illustrate communication issues between components. There are times when we develop apps that have a requirement: Click on an item in Listfragment, detailfragment show the corresponding data, and the relationship between components is as follows:

The code to achieve the above requirements corresponds to the following:
Define functions in Detailfragment:

//函数定义好了,如何被调用?publicvoidloadDetails(Item items) {    ...}

interface defined in Listfragment:

interface Contract {    void onItemSelected(Item item);}//传递到Activity中((Contract)getActivity)).onItemSelected(item);

Activity Implementation Interface:

publicclass MyActivity implements ListFragment.Contract {    publicvoidonItemSelected(Item item) {        DetailFragment detailFragment = (DetailFragment)getFragmentManager().        findFragmentBy...;        detailFrasgment.loadDetails(item);    }}

Eventbus makes communication between components simpler, and communication between components is as follows:

Eventbus consists of 4 basic components: Publisher, Subscriber, event, and bus. The relationship of 4 is as follows:

Basic usage

1 Defining an Event
public class MyEvent {}
2 subscribers ' Registration
Eventbus.getdefault (). Register (this);
3 Publishing Events
Eventbus.getdefault (). Post (event);
4 Receiving events
public void OnEvent (MyEvent event);

Eventbus Event handling method: OnEvent

1 when registering subscribers, Eventbus scans the event handler functions in Subscribers
2 naming convention: Start with OnEvent, public, no return value, only one parameter

When an event is published, Eventbus is determined by the parameter type to determine which subscriber responds to the event.

Implementing List/details Scenarios with Eventbus

Step 1: define the event Class

publicclass ItemSelectedEvent {  publicfinal Item item;  publicItemSelectedEvent(Item item) {    this.item = item;  }}

Step 2: Sending events in Listfragment

EventBus.getDefault().post(new ItemSelectedEvent(item));

Step 3: Handling Events in Detailfragment

publicvoidonEvent(ItemSelectedEvent event) {    ...}

[Click to download Source] (http://download.csdn.net/detail/lmj623565791/8126089)

Threading model for Eventbus

Why do you define an event model? Because the use of the threads in Android has the following limitations:

1 The main thread cannot be blocked, UI updates are in the main thread, time consuming operations such as network processing in the background thread
2 events can be sent and processed in different threads

By using the threading model of Evenbus, we can define the type of thread that handles events. There are four types of threading models in Eventbus: Postthread,mainthread,backgroundthread,async, which are described below.
Postthread
The default threading model, which events are published and received on the same thread, is suitable for tasks that have a very short time to complete to avoid blocking the UI. Cases:

// Called in the same thread (default)publicvoidonEvent(MessageEvent event) {    log(event.message);}

Mainthread
The subscriber's event handling method is called on the main thread and is suitable for handling small overhead events to avoid blocking the main thread. Cases:

// Called in Android UI‘s main threadpublicvoidonEventMainThread(MessageEvent event) {    textField.setText(event.message);}

Backgroundthread
The subscriber's event handling is called in the background. If the event send thread is in the main thread, Eventbus will use a background thread to send the event one at a time.

// Called in the background threadpublicvoidonEventBackgroundThread(MessageEvent event){    saveToDisk(event.message);}

Async
Event processing is located on a separate thread, which is often neither the thread that sends the event, nor the thread. Using this model for event sending does not need to wait for event processing before returning, suitable for processing time-consuming operations, such as requesting a network. Eventbus internally uses a thread pool to manage multiple threads. Cases:

// Called in a separate threadpublicvoidonEventAsync(MessageEvent event){    backend.send(event.message);}
Summary:

This article describes the functionality and usage of Eventbus, and in the next article I will describe the implementation principles and internal data structures of Eventbus.

Examples of Eventbus for Android

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.