EvenBus3.0中文翻译(四)Sticky Events

来源:互联网 发布:手机预装软件下载 编辑:程序博客网 时间:2024/05/14 21:04

水平有限,仅供参考

原文地址

Sticky Events

Sticky 事件

Some events carry information that is of interest after the event is posted. For example,

an event signals that some initialization is complete. 

Or if you have some sensor or location data and you want to hold on the most recent values. 

Instead of implementing your own caching, you can use sticky events.

EventBus keeps the last sticky event of a certain type in memory. 

The sticky event can be delivered to subscribers or queried explicitly. 

Thus, you dont need any special logic to consider already available data.

感兴趣的的事件发送后事件将会携带感兴趣的数据信息。例如,你想抓住最新的一些初始化完成的事件信号。

或者如果你想抓住最新的一些传感器或位置信息。而不是执行你的缓存,你可以使用Sticky 事件。

EventBus 可以在内存中保持最新的特定类型的事件。该Sticky事件可以明确查询到或者交付给订阅者。

因此,你不需要任何特殊的逻辑来考虑已存在的可用数据。

Sticky Example

Sticky 例子

Lets say, a sticky event was posted some time ago:

比方说, 不久前发送了一个Sticky 事件:

EventBus.getDefault().postSticky(new MessageEvent("Hello everyone!"));

Now, the sticky event was posted, a new Activity gets started.

 During registration all sticky Subscriber methods will immediately get the previously posted sticky event:

现在,这个Sticky 事件已被发送,一个新的Activity开始了。

在注册完成后,所有的sticky 订阅者的订阅方法将会立即接收到先前发送的Sticky 事件:

@Overridepublic void onStart() {    super.onStart();    EventBus.getDefault().register(this);}@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)public void onEvent(MessageEvent event) {// UI updates must run on MainThread// UI 更新必须运行在主线程    textField.setText(event.message);}@Overridepublic void onStop() {    EventBus.getDefault().unregister(this);} 

Getting and Removing sticky Events manually

手动获取和删除Sticky 事件

As you saw in the previous paragraph,

 the last sticky event gets delivered automatically to matching subscribers when they register.

 But sometimes it may be more convenient to manually check on sticky events.

 Also it may be necessary to remove (consume) sticky events so that they wont be delivered anymore. 

Example:

正如你在前一段所看到的,最新的一个Sticky 事件会自动传递给与其匹配的已注册的订阅者。

但有时需要更灵活的地手动获取Sticky 事件。也有时需要删除(消耗掉)Sticky 事件,使他们停止发送。

例子:

MessageEvent stickyEvent = EventBus.getDefault().getStickyEvent(MessageEvent.class);// Better check that an event was actually posted before//使用前确保事件的存在if(stickyEvent != null) {// "Consume" the sticky event// 删除(消耗掉)Sticky 事件    EventBus.getDefault().removeStickyEvent(stickyEvent);// Now do something with it// 现在用它做点什么}

The method removeStickyEvent is overloaded: when you pass in the class,

 it will return the previously held sticky event. Using this variation, 

we can improve the previous example:

removeStickyEvent(Object event)方法的使用:调用这个方法,它将返回先前持有的Sticky 事件。

利用这种特性,我们可以改善先前的例子:

MessageEvent stickyEvent = EventBus.getDefault().removeStickyEvent(MessageEvent.class);// Better check that an event was actually posted before// 使用前确保事件的存在if(stickyEvent != null) {     // Now do something with it // 现在用它做点什么}





0 0
原创粉丝点击