简体   繁体   English

RxJava2从侦听器创建Flowable并在最后删除侦听器

[英]RxJava2 create Flowable from listener and remove listener at the end

My use case is related to using RxJava2 with Firebase Database. 我的用例与将RxJava2与Firebase数据库一起使用有关。

I have a DatabaseReference and I can register value listeners to it. 我有一个DatabaseReference ,我可以为它注册值监听器。 I can transform it into a flowable like this: 我可以把它变成像这样的流动:

disposable = Flowable.create<DataSnapshot>({ s ->
            dbRef.addValueEventListener(object : ValueEventListener {
                override fun onCancelled(p0: DatabaseError) {...}

                override fun onDataChange(value: DataSnapshot) {
                    s.onNext(value)
                }
            })
        }, BackpressureStrategy.BUFFER)
        .subscribe(...)

I would like to be able to remove the listener when the disposable is disposed. 我希望能够在丢弃一次性物品时移除听众。 Any idea how I can do that? 知道我怎么能这样做吗?

I saw that in rxjava 1 there was this possibility maybe, but it's not available in rxjava2 我在rxjava 1中看到了这种可能性 ,但它在rxjava2中不可用

With RxJava2 you need to use the setCancellable() method, and put your listener removal code there. 使用RxJava2,您需要使用setCancellable()方法,并将侦听器删除代码放在那里。
This is much like Emitter.setCancellation() from RxJava1, when creating Observable with Observable.fromEmitter() . 当使用Observable.fromEmitter()创建Observable时,这与RxJava1中的Emitter.setCancellation()非常相似。

Take also this note by akarnokd regarding cancellation: 听取akarnokd关于取消的说明:
"But note that unless the create logic gives up the scheduler (by terminating or going async), the cancellation logic may not ever execute due to same-pool livelock." “但请注意,除非创建逻辑放弃调度程序(通过终止或异步),否则取消逻辑可能永远不会执行,因为相同的池活动锁定。” ( RxJava 2: always unsubscribe on the .subscribeOn(..) scheduler? ) RxJava 2:总是取消订阅.subscribeOn(..)调度程序?

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

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