rx-javareactive-programmingrxandroidblerx-kotlin

refCount keeping connection even after an error


I'm using refCount to hold onto a BLE connection for 5 mins. This works well until I have a connection issue, refCount still keeps the connection and replay replays the error.

Is there a way I can make either make refCount disconnect as soon as there is an error, or make replay not replay errors?

        bleDevice
            .establishConnection(false)
            .replay(1)
            .refCount(1, 5, TimeUnit.MINUTES)

Solution

  • The easy way to achieve what you want is by using RxJava 3 refCount operator. You can use an RxJava 2 <=> 3 interoperability library RxJavaBridge.

    val connectionObservable = bleDevice
        .establishConnection(false)
        .`as`(RxJavaBridge.toV3Observable())
        .replay(1)
        .refCount(1, 5, TimeUnit.MINUTES)
        .to(RxJavaBridge.toV2Observable()) // optional if you want to stick to RxJava 3