简体   繁体   English

建议在EventBus / Otto中使用Handler?

[英]Recommended to use Handler with EventBus/Otto?

With libraries like Otto and EventBus I wonder whether it still makes sense to use Handler : 有了像Otto和EventBus这样的库,我想知道使用Handler是否仍然有意义:

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Handler允许您发送和处理与线程的MessageQueue关联的Message和Runnable对象。 Each Handler instance is associated with a single thread and that thread's message queue. 每个Handler实例都与一个线程和该线程的消息队列相关联。

How can handlers be used in addition to event bus libraries? 除事件总线库外,如何使用处理程序? I recon it is sufficient to use vanilla threads and send messages directly over the event bus or am I missing something here? 我认为使用vanilla线程并直接通过事件总线发送消息就足够了,或者我在这里遗漏了什么?

Usually you use event bus libraries and handlers for different problems. 通常,您会针对不同的问题使用事件总线库和处理程序。

Event bus libraries allow information consumers to subscribe to particular events and producers to publish them, without the publisher and subscriber components needing to know really anything about each other. 事件总线库允许信息消费者订阅特定事件和生产者以发布它们,而发布者和订阅者组件不需要知道关于彼此的任何事情。 More than one consumer can subscribe to an event; 不止一个消费者可以订阅一个活动; more than one producer may publish it. 不止一个制作人可以发布它。 The model is many-to-many. 该模型是多对多的。

Handlers on the other hand are one-to-one. 另一方面,处理程序是一对一的。 You send a Message or post a Runnable and it gets processed only by the target Handler once, unless removed before execution. 您发送消息或发布Runnable,它只由目标处理程序处理一次,除非在执行之前删除。 The core purpose of handlers is scheduling work on a thread, as mentioned in the documentation you quoted. 处理程序的核心目的是在线程上安排工作,如您引用的文档中所述。

You can use Handlers and Messages to implement an event bus. 可以使用处理程序和消息来实现事件总线。 For example, have the bus be a collection of Handlers and the events Messages. 例如,让总线成为Handlers和事件Messages的集合。 The event messages get sent to those handlers that have registered themselves as subscribers to a particular event type. 事件消息被发送给那些已将自己注册为特定事件类型的订阅者的处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM