vjnjc
V2EX  ›  Android

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

  •  
  •   vjnjc · Jun 21, 2017 · 13216 views
    This topic created in 3254 days ago, the information mentioned may be changed or developed.

    背景

    以前用的 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 replies    2017-06-22 08:39:18 +08:00
    pual
        1
    pual  
       Jun 21, 2017   ❤️ 1
    在主线程构造的匿名内部类持有外部类的引用, 在 onDestroy 等地方 Dispose 可以避免内存泄露
    Chrisplus
        2
    Chrisplus  
       Jun 21, 2017   ❤️ 1
    vjnjc
        3
    vjnjc  
    OP
       Jun 21, 2017
    @Chrisplus 终于看到现成的了,多谢!
    3pmtea
        4
    3pmtea  
       Jun 21, 2017
    subject 类有个 ofType 方法,可以用来过滤事件类型
    订阅是需要释放的,用 CompositeDisposable 收集起来,在 onDestroy 的时候释放,或者用 rxlifecycle

    另外,最好是给个 BaseEvent 基类,不然 bus 可以 post 任意 object 的话,一不小心自己或者队友就有可能会 post 一个毫无干系的东西,然后收不到事件,编译器也不会叫,导致 de 半天的 bug
    vjnjc
        5
    vjnjc  
    OP
       Jun 21, 2017
    @3pmtea 多谢。暂时没有做 BaseEvent,因为我有个类似 BaseHttpResponse 的东西,eventBus 的 object 和 http 的 object 是同一个。因为单继承。。。
    Cabana
        6
    Cabana  
       Jun 22, 2017 via Android
    不知道你有没有用 j 大的 rxrelay 来发布事件,你如果使用 rx 原生的 subjects 去发布事件的话,在遇到 error 后会导致后续事件无法发布
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1047 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 19:12 · PVG 03:12 · LAX 12:12 · JFK 15:12
    ♥ Do have faith in what you're doing.