维护事件处理的优秀工具:org.greenrobot.EventBus 使用介绍

使用开源的org.greenrobot.EventBus可以更好地维护事件处理,取代反射(参考:https://blog.csdn.net/haoranhaoshi/article/details/103816810),取代自写监听(参考:https://blog.csdn.net/haoranhaoshi/article/details/84250934)。

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class EventBusTest {
    public EventBusTest(){
        // 本类或子类必须有@Subscribe的pulic且非static的方法
        EventBus.getDefault().register(this);
    }

    public static void main(String[] args) {
        new EventBusTest();
        Event event = new Event();
        event.setType(EventType.TEST);
        event.setData("Event Bus Test ", 1);
        // post方法可以和注册、取消注册、执行事件这三个方法一个类,也可以不是一个类
        // EventBus.getDefault().unregister(this);注册、取消注册是一个对象
        EventBus.getDefault().post(event);
    }

    /**
     * EventBus的响应方法加注解@Subscribe(threadMode = ThreadMode.MAIN),响应方法名无特殊要求
     * 此方法必须public
     * 此方法必须非 static
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBusAction(Event event) {
        if(EventType.TEST.equals(event.getType())){
            Object[] data = (Object[])event.getData();
            System.out.println(data[0]);
            System.out.println(data[1]);
        }
    }
}
public class Event {
    private String type;
    private Object data;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object... data) {
        this.data = data;
    }
}
public class EventType {
    public static final String TEST = "test";
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hao.test</groupId>
    <artifactId>event-bus</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.greenrobot</groupId>
            <artifactId>eventbus</artifactId>
            <version>3.1.1</version>
        </dependency>
    </dependencies>
</project>

注意:EventBus.getDefault().post(event);所在类A必须能找到EventBus.getDefault().register(this);所在类B。比如在模块化工程中,类B所在模块2必须导出类B所在的包,即模块2的module-info.java必须exports 类B所在的包(此包不能是类B所在包的上级包)。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风铃峰顶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值