什么是EventBus

EventBus是一款针对Android优化的发布/订阅事件总线。

 

EventBus有什么用

线程之间传递消息

 

为什么使用EventBus

1.开销小,几行代码就可以实现。

2.发送者和接收者解耦。

 

下载地址

https://github.com/greenrobot/EventBus

 

怎么使用EventBus

代码示例

1.先自定义一个消息传输类

public class msgType {
     public msgType(){}
}

2.使用时进行注册

eventBus.register(this);

3.发送需要传输的消息,借助自定义的传输类

eventBus.post(new msgType event);

4.在你需要接收信息的地方定义方法进行接收(方法体内就是传输类)

public void onEvent(msgType event) {}

5.解除注册

eventBus.unregister(this);

 

实战

使用前先进行注册

@SpringBootApplication
public class CollectorServerApplication implements CommandLineRunner
{
    //获取XML配置
    private static AgreementConfig config = AgreementConfig.getInstance();

    public static void main(String[] args)
    {
        SpringApplication.run(CollectorServerApplication.class, args);
        //注册事件广播,事件总线
        EventBusUtil.register(new EventListener());
        EventBusUtil.register(new ConversionListener());

        new NettyServerInit(config);
    }
}

消息发送

 将封装好的数据进行传递

EventBus.publish(builder);
@Override
    public Object handler(DecoderMetaData metaData)
    {
        List<String> data = metaData.getBody();
        String functionCode = data.get(1);
            SmartGatewayData gatewayData = handlerF4(data);
            Map<String, Object> map = MessageUtils.ObjectToMap(gatewayData);
            //加入proId
            map.put("proId", metaData.getProId());
            TopicBuilder builder = new TopicBuilder.Builder()
                    .setTopicName("topic名字")
                    .setDivceName("物联网关001")
                    .setTag("gateway")
                    .setData(map)
                    .setTypeName("网关元数据")
                    .setDivceType(DeviceTypeEnum.NETGATEWAY.getTypeName())
                    .setChannel(metaData.getChannel()).builder();
            EventBus.publish(builder);
        }
        return null;
    }

EventBus工具类

public class EventBus
{
    /**
     * 设备信息注册
     * @param deviceInfo
     */
    public static void registered(DeviceInfo deviceInfo)
    {
        EventBusUtil.asyncPost(deviceInfo);
    }

    /**
     * 广播数据域
     * @param topicBuilder
     */
    public static void publish(TopicBuilder topicBuilder)
    {
        //EventBusUtil.post(topicBuilder);
        EventBusUtil.asyncPost(topicBuilder);
    }
}

根据传入对象进行监听

关键

@Subscribe 数据共享
/**
     * 处理路由
     * @param metadata
     */
    @Subscribe
    @AllowConcurrentEvents
    public void handleRoute(TopicMetadata metadata)
    {
    业务处理   }

这样就可以监听发送来的消息,如果是相同的对象,则进行接收

关键就是两边的参数要对上,这样才能接收到消息。

更多文章请关注《万象专栏》