NordicSemiconductor / Android-BLE-Library

A library that makes working with Bluetooth LE on Android a pleasure. Seriously.
BSD 3-Clause "New" or "Revised" License
1.99k stars 414 forks source link

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

Open MaiHeu opened 1 year ago

MaiHeu commented 1 year ago

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.

philips77 commented 1 year ago

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

MaiHeu commented 1 year ago

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 :)