Android-BLE-Library icon indicating copy to clipboard operation
Android-BLE-Library copied to clipboard

ble-livedata allows non-nullable MutableLiveData to be null in kotlin

Open MaiHeu opened this issue 2 years ago • 2 comments

I have the following piece of code:

private val _connectedPeripheral: MutableLiveData<MyDevice> = MutableLiveData()
public val connectedPeripheral: LiveData<MyDevice>
    get() = _connectedPeripheral
private val bleManager = MyBleManager(context)

public fun disconnect() {
    if (bleManager.currentConnectedDevice == null)
        return
    bleManager.disconnect()
    _connectedPeripheral.value = null //this should not be allowed, as the LiveData wasn't declared nullable
    startScanning()
}

It compiles and runs, though it would add the possibility of a NPE where it isn't expected. With the current androidx.lifecycle:lifecycle-livedata-core-ktx:2.6.1 package it rightfully gets marked by Android Studio as error and thus does not compile.

MaiHeu avatar Apr 17 '23 09:04 MaiHeu

Hello, are you're suggesting updating dependencies? The library module already depends on 2.6.1: https://github.com/NordicSemiconductor/Android-BLE-Library/blob/004e6645dfb391c253c13a8b75d38a86b0aeacc2/ble-livedata/build.gradle#L32

philips77 avatar Apr 17 '23 09:04 philips77

I rather thought it's due to an implementation error, but digging further into it it seems the issue is a java <-> kotlin one. I can reproduce said problem when exchanging the ble-livedata with androidx.lifecycle:lifecycle-livedata:2.6.1

Internally, the package androidx.lifecycle:lifecycle-livedata-core-ktx seems to ensure and enforce the null safety.

This issue would probably fit with #483 for a kotlin specific package :)

MaiHeu avatar Apr 17 '23 11:04 MaiHeu