V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
vjnjc
V2EX  ›  Android

用 rxAndroid2 写了个 eventbus,求给点意见。

  •  
  •   vjnjc · 2017-06-21 17:02:46 +08:00 · 4753 次点击
    这是一个创建于 2498 天前的主题,其中的信息可能已经有所发展或是发生改变。

    背景

    以前用的 otto 来持有 eventbus,今天一看他们官网居然不玩了。。。于是根据官方指导引入了 rxAndroid 来实现 bus。跟着这份手册写了个简单的 bus

    Bus 实现

    https://gist.github.com/jiachenning/34236178ddd5d0d1154a21b38c909429

    Bus 用法

    _rxBus.send(new UserLogin());
    _rxBus.toObserverable()
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(@NonNull Object obj) throws Exception {
                        if(obj instanceof UserNotLoginException){
                            Toaster.showShort(activity, "Userlogin");
                        }else {
                            Toaster.showShort(activity, "unknown type");
                        }
                    }
                });
    

    一些疑问

    • 有一个 event 被 send 出来后,所有相关的 consumer 都会被 invoke,然后用 instance of 关键词来筛选。能不能改成 send(topic, event)的这种方式,这样在 invoke consumer 的前能筛选。
    • 这种绑定会有泄露问题吗?
    • 还有没有欠考虑的地方?(第一天用 rxJava 根本没感觉啊
    6 条回复    2017-06-22 08:39:18 +08:00
    pual
        1
    pual  
       2017-06-21 17:14:15 +08:00   ❤️ 1
    在主线程构造的匿名内部类持有外部类的引用, 在 onDestroy 等地方 Dispose 可以避免内存泄露
    Chrisplus
        2
    Chrisplus  
       2017-06-21 17:15:53 +08:00   ❤️ 1
    vjnjc
        3
    vjnjc  
    OP
       2017-06-21 17:20:11 +08:00
    @Chrisplus 终于看到现成的了,多谢!
    3pmtea
        4
    3pmtea  
       2017-06-21 17:41:45 +08:00
    subject 类有个 ofType 方法,可以用来过滤事件类型
    订阅是需要释放的,用 CompositeDisposable 收集起来,在 onDestroy 的时候释放,或者用 rxlifecycle

    另外,最好是给个 BaseEvent 基类,不然 bus 可以 post 任意 object 的话,一不小心自己或者队友就有可能会 post 一个毫无干系的东西,然后收不到事件,编译器也不会叫,导致 de 半天的 bug
    vjnjc
        5
    vjnjc  
    OP
       2017-06-21 17:56:36 +08:00
    @3pmtea 多谢。暂时没有做 BaseEvent,因为我有个类似 BaseHttpResponse 的东西,eventBus 的 object 和 http 的 object 是同一个。因为单继承。。。
    Cabana
        6
    Cabana  
       2017-06-22 08:39:18 +08:00 via Android
    不知道你有没有用 j 大的 rxrelay 来发布事件,你如果使用 rx 原生的 subjects 去发布事件的话,在遇到 error 后会导致后续事件无法发布
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5300 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 09:02 · PVG 17:02 · LAX 02:02 · JFK 05:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.