0

I have the following code using an. RxAndroidBle Bluetooth Low Energy Connection:


private val connectionDisposable = CompositeDisposable()

private fun writeBle(writeCharacteristicUuid: UUID, command: ByteArray)
if (bleDevice.connectionState == RxBleConnection.RxBleConnectionState.CONNECTED) {

            activeConnection
                .flatMapSingle {
                    it.writeCharacteristic(writeCharacteristicUuid, command)
                }
                .subscribe({
                    Log.d(
                        TAG,
                        "${connectionDisposable.size()} - Command successful: ${it.toHexString()}"
                    )
                })
                { Log.e(TAG, "Error executing command: $it") }
                .let { connectionDisposable.add(it) }
        } else {
            Log.e(TAG, "You are not connected")
        }
}

The connectionDisposable is .clear()ed when the connection to the device is closed. But until then several hundreds, thousands or more disposable will land in the connectionDisposable.

I am not completely clear if this presents a Problem in regard to memory usage, or whether I am missing the right way to execute a lot of write commands (that should not be send simultaneously to the device).

WeGi
  • 1,908
  • 1
  • 21
  • 33
  • Why are you collecting the disposables if you aren't going to dispose them anyway? – adnan_e Oct 20 '22 at 13:15
  • 2
    The disposables will dispose themselves when the request finishes. They are there for you to dispose them preemptively in case you "don't need it anymore" (e.g. a network request that you started is no longer needed due to the user cancelling) – adnan_e Oct 20 '22 at 13:16
  • The disposable object. however, will remain in memory because you keep a reference to it, and this will surely accumulate and may lead to OOM, unless you clear them periodically. – adnan_e Oct 20 '22 at 13:17
  • I was not aware, that the disposables are disposing themselves, when the write request is finished. This is the reason why I am collecting them (to dispose when the connection is severed). – WeGi Oct 20 '22 at 13:21
  • 1
    There is now an overload for `subscribe` where you can specify the composite that will hold onto the disposable and upon termination, it will remove said disposable. Should stop the "leak" between clears. http://reactivex.io/RxJava/3.x/javadoc/io/reactivex/rxjava3/core/Observable.html#subscribe-io.reactivex.rxjava3.functions.Consumer-io.reactivex.rxjava3.functions.Consumer-io.reactivex.rxjava3.functions.Action-io.reactivex.rxjava3.disposables.DisposableContainer- – akarnokd Oct 21 '22 at 07:43
  • 1
    What @akarnokd suggests is a good idea. Alternatively you could create a Subject that would emit a POJO with `UUID` and `byte[]` and mix it into the chain of Observables of the `RxBleConnection`. – Dariusz Seweryn Oct 26 '22 at 20:13

0 Answers0