Introduction to the use of EventBus framework

Introduction to the use of EventBus framework

.

EventBus

Introduction

EventBus is a publish-subscribe event bus optimized for Android. It simplifies the communication between components and between components and background threads in the application. The advantages are low overhead, more elegant code, and decoupling of sender and receiver.

.

The three elements of EventBus

  1. Event: Event, can be any type of object

  2. Subscriber: event subscriber, in EventBus 3.0 before we have to define in a few methods onEvent beginning, namely onEvent, onEventMainThread, onEventBackgroundThreadand onEventAsync, and in the name of the method 3.0 after the event handler can freely take, but it needs to add comments @subscribe, and Specify the thread model, the default is POSTING.

  3. Publisher: Event publisher, can send events anywhere in any thread and call them directly. In general, you can get an EventBus object by using EventBus.getDefault(), and then call the post(Object) method.

.

Four threading models

EventBus3.0 has four threading models, namely:

  • POSTING (default): Indicates that the thread of the event processing function and the thread of the event are in the same thread

  • MAIN: Indicates that the thread of the event processing function is in the main thread (UI) thread, so time-consuming operations cannot be performed here

  • BACKGROUND: Indicates that the thread of the event processing function is in the background thread, so UI operations cannot be performed. If the thread that publishes the event is the main thread (UI thread), then the event processing function will start a background thread. If the thread that publishes the event is a background thread, the event processing function uses this thread

  • ASYNC: Indicates that no matter which thread the event is published, the event processing function will always create a new child thread to run, and UI operations cannot be performed either

You can set the threading model when handling events, as shown below:

//设置线程模型
@Subscribe(threadMode = ThreadMode.MAIN)
public void XXXX(MessageWrap message) {
    
    
    //消息的内容
	Log.d("接收的信息内容:",message);
}

.

.

Basic usage of EventBus

Introduce dependencies

Before using, the build.gradlefollowing dependencies must be introduced:

dependencies{
    
    
	implementation 'org.greenrobot:eventbus:3.1.1'
}

.

The use of EventBus is divided into the following 5 steps:

.

1. Customize an event class

Role: Use the object as communication information within the program

public class MessageEvent {
    
    

    public final String message;

    private MessageEvent(String message) {
    
    
        this.message = message;
    }

    public static MessageEvent getInstance(String message) {
    
    
        return new MessageWrap(message);
    }
}

2. Register the event where you need to subscribe to the event

Register the event in MainActivity as follows:

public class MainActivity extends AppCompatActivity{
    
    

	@Override
	protected void onCreate (Bundle savedInstanceState){
    
    
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_,ain);
		
		initData();
	}

	public vaid init(){
    
    
		//注册事件
		EventBus.getDefault().register(this);
	}
}

3. Send event

Created SecondActivity to publish messages, the code is as follows:

public class SecondActivity extends AppCompatActivity{
    
    

	@Override
	protected void onCreate (Bundle savedInstanceState){
    
    
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_,ain);
		
		sendMessag();
	}

	public vaid sendMessag(){
    
    
		//发送消息
		EventBus.getDefault().post(new MessageEvent("你好!我是萝莉"));
	}
}

4. Handle the event on the event receiver

Receive events and modify processing in MainActivity, as shown below:

public class MainActivity extends AppCompatActivity{
    
    

	@Override
	protected void onCreate (Bundle savedInstanceState){
    
    
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_,ain);
		
		initData();
	}

	public vaid init(){
    
    
		//注册事件
		EventBus.getDefault().register(this);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void GetMessage(MessageWrap message) {
    
    
        //打印消息的内容
		Log.d("接收的信息内容:",message);
	}
}

5. Cancel event subscription

In MainActivity the onDestroy()unsubscribe event method, as follows:

public class MainActivity extends AppCompatActivity{
    
    

	@Override
	protected void onCreate (Bundle savedInstanceState){
    
    
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_,ain);
		
		initData();
	}

	public vaid init(){
    
    
		//注册事件
		EventBus.getDefault().register(this);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void GetMessage(MessageWrap message) {
    
    
        //打印消息的内容
		Log.d("接收的信息内容:",message);
	}

	@Override
	protected void onDestroy(){
    
    
		super.onDestroy();
		//取消注册事件
		EventBus.getDefault().unregister(this);
	}
}

6. Add ProGuard obfuscation rules

In proguard-rules.proadd confusion rules file

#eventbus打包混淆
- keepattributes *Annoation*
- keepclassmembers class **{
    
    
	@org.greenrobot.eventbus.Subscrile<methods>;
}

-keep enum org.greenrobot.eventbus.ThreadMode{
    
     *; }
# Only requirend if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.
ThrowableFailurEvent{
    
    
	<init>(java.lang.Throwable);
}

.

.

Introduction of EventBus sticky events

EventBus also supports sending sticky events, that is, you can receive the event by subscribing to the event after sending the event, which is similar to sticky broadcasting.

.

In order to verify sticky events, we modify the previous code as shown below

1. Subscribers deal with sticky events

Write a new method in MainActivity to handle sticky events

@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void GetViscosityMessage(MessageWrap message) {
    
    
    //打印消息的内容
	Log.d("接收的黏性信息内容:",message);
}

2. Send sticky events

Send sticky events in SecondActivity

public vaid sendMessag(){
    
    
	//发送消息
	EventBus.getDefault().postSkticky(new MessageEvent("你好!我是萝莉"));
}

.

.

Introduction to EventBus subscription priority

In Subscribe注解a total of three parameters, where the priorityparameters are used to specify the priority subscription method is a value of an integer type, the default is 0, said that the greater the value of the priority. When an event is published, the subscription method with higher priority will receive the event first.

use:

@Subscribe(threadMode = ThreadMode.POSTING, priority = 0)

note:

  • Only when the two subscription methods use the same ThreadMode parameter, their priority will be consistent with the value specified by priority

  • Only when the ThreadMode parameter of a subscription method is POSTING, it can stop the continued distribution of the event

Specific use:

public class MainActivity extends AppCompatActivity{
    
    

	// 用来判断是否需要停止事件的继续分发
	private boolean stopDelivery = false;

	@Override
	protected void onCreate (Bundle savedInstanceState){
    
    
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_,ain);
		
		initData();
	}

	public vaid init(){
    
    
		//注册事件
		EventBus.getDefault().register(this);
	}

	/*-------------------- 对事件进行处理 --------------------*/
	@Subscribe(threadMode = ThreadMode.POSTING, priority = 0)
	public void onGetMessage(MessageWrap message) {
    
    
      	//打印消息的内容
		Log.d("接收的信息内容:",message);
	}

	// 订阅方法,需要与上面的方法的threadMode一致,并且优先级略高
	@Subscribe(threadMode = ThreadMode.POSTING, sticky = true, priority = 1)
	public void onGetStickyEvent(MessageWrap message) {
    
    
		//打印消息的内容
		Log.d("接收的信息内容:",message);			

	    if (stopDelivery) {
    
    
	        // 终止事件的继续分发
	        EventBus.getDefault().cancelEventDelivery(message);
	    }
	}

	@Override
	protected void onDestroy(){
    
    
		super.onDestroy();
		//取消注册事件
		EventBus.getDefault().unregister(this);
	}
}

.

.

supplement:

Implement RxBus with RxJava

If you have introduced RxJava in your project, you can use RxJava to implement the event bus RxBus instead of EventBus and otto.

Introduce dependencies

Before using, the build.gradlefollowing dependencies must be introduced:

dependencies{
    
    
	implementation 'io.reactivex:rxjava:1.2.0'
	implementation 'io.reactivex:rxandroid:1.2.1'
}

1. Create RxBus

First create RxBus. The RxBus here only supports basic functions. If readers want to add some functions, they can customize them. The code is as follows:

public class RxBus{
    
    
	private static volatile RxBus rxBus;
	private final Subject<Object,Object> subject = new SerializedSubject<>(PublishSubject.create);

	//使用单例模式的双重检查模式
	public static RxBus getInstance(){
    
    
		if(rxBus == null){
    
    
			synchronized(RxBus.class){
    
    
				if(rxBus == null){
    
    
					rxBus = new RxBus();
				}
			}
		}
		return rxBus;
	}

	public void post(Object ob){
    
    
		subject.onNext(ob);
	}

	public <T> Observable<T> toObservable(Class<T> eventType){
    
    
		//ofType方法中包含了filter和cast的操作。
		//通过filter操作符来判定是否是指定的类型,如果不是就不提交 给订阅者。
		//cast操作符则用来将Observable转换成指定类型的Observable
		return subject.ofType(eventType);
	}

}

2. Send event

Send events in MainActivity

public class MainActivity extends AppCompatActivity{
    
    

	@Override
	protected void onCreate (Bundle savedInstanceState){
    
    
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		initData();
	}

	public vaid init(){
    
    
		//发送事情
		RxBus.getInstance().post(new MessageEvent("用RxJava实现RxBus"));
	}
}

3. Receive events

Receive events in TwoActivity as follows:

public class TwoActivity extends AppCompatActivity{
    
    
	
	private Subscriber subscription;
	
	@Override
	protected void onCreate (Bundle savedInstanceState){
    
    
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_two);
		
		initData();
	}

	public vaid init(){
    
    
		//接收消息
		subscription = RxBus.getInstance.toObservable(MessageEvent.class).subscribe(new Action1<MessageEvent>(){
    
    
		@Override
		public void call(MessageEvent messageEvent){
    
    
			Log.v("MainActivity发送过来的消息:",messageEvent.getMessage());
			}
		}
	}

	@Override
	protected void onDestroy(){
    
    
		super.onDestroy();
		//取消订阅事件
		if(subscription != null && !subscription.isUnsubscribed()){
    
    
			subscription.unsubscribe();
		}
	}
}

Guess you like

Origin blog.csdn.net/weixin_42324979/article/details/112172736