EventBus

EventBus模式也被称为Message Bus模式或者发布者/订阅者(publish/subscribe)模式。可以让两个组件相互通信(publisher发送event到bus,bus在把时间分发到subscriber),但是他们之间并不互相知晓(即不用实现接口,通过接口进行通信)。
这里写图片描述

EventBus的使用步骤:

1.定义事件

public class TestEvent {
    String info;
    TestEvent(String info){
        this.info = info;
    }

    public String getInfo(){
        return info;
    }
}

2.subscriber准备工作:
eventBus.register(this);//注册
public void onEvent(TestEvent event)//定义接收event函数
3.发送event
eventBus.post(event);

**

Event Bus 的ThreadModes

**
PostThread: subscriber会在发送event的线程中被调用。事件处理函数会在次线程中被调用。

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

**MainThread:**subscriber会在主线程中被调用。如果发送event实在主线程中,事件处理函数就会立即被调用。

 // Called in Android UI's main thread
    public void onEventMainThread(MessageEvent event) {
        textField.setText(event.message);
    }

如果发送event不是在主线程,由Event Bus 切换线程(之后会分析到)。

BackgroundThread: Subscriber will be called in a background thread. If posting thread is not the main thread, event handler methods will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single background thread that will deliver all its events sequentially.

  // Called in the background thread
    public void onEventBackgroundThread(MessageEvent event){
        saveToDisk(event.message);
    }

Async: Event handler methods are called in a separate thread. This is always independent from the posting thread and the main thread.(事件处理函数将会在另一个线程中被调用。此线程独立于发送事件的进程和主线程)

// Called in a separate thread
    public void onEventAsync(MessageEvent event){
        backend.send(event.message);
    }

**注意:**EventBus在哪个线程调用subscriber的onEventXX()函数,取决于onEventXX的名字。 eg:onEventMainThread()会在主线程中被调用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值