在尝试编写一段负责发现蓝牙设备的代码时,我遇到了一个非常令人沮丧的问题。
根据 Android Studio,这段代码是正确的:
fun discoverDevices(): Observable<BluetoothDevice> {
val discovered: HashSet<BluetoothDevice> = HashSet()
return bluetoothUtil.startDiscovery()
.flatMapObservable { discoveryStarted ->
if(discoveryStarted) {
RxBroadcastReceiver.create(appContext, IntentFilter().apply {
addAction(BluetoothDevice.ACTION_FOUND)
addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
})
} else {
Observable.error(Throwable("Discovery couldn't be started"))
}
}
.takeUntil { intent ->
intent.action == BluetoothAdapter.ACTION_DISCOVERY_FINISHED
}
.map { intent ->
var bluetoothDevice: BluetoothDevice? = null
if(intent.action == BluetoothDevice.ACTION_FOUND) {
bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
}
if(bluetoothDevice != null && !discovered.contains(bluetoothDevice))
bluetoothDevice
else
null
}
}
函数声明它返回 Observable<BluetoothDevice>
尽管很明显 map 函数将返回 BluetoothDevice?
.此外,我试图通过附加
.filter {
it != null
}
到链的末尾,条件it != null
突出显示为“始终为真”并且返回值突然变为 Observable<BluetoothDevice?>
.这太令人沮丧了,我似乎找不到解决这个奇怪问题的方法。
这是 Android Studio 的错误还是我做错了什么?
最佳答案
这有一个非常简单的解释:null
值在 RxJava2 中不支持。
使用 null
将在运行时抛出 NullPointerException
,如下所述:What's different in 2.0 .
在您的特定情况下,IDE 将表达式突出显示为“始终为真”,因为 RxJava2 运算符不支持可空类型,因此它永远不会发出一个。
关于android - Kotlin 在使用 RxJava2 时错误地推断类型可空性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50564072/