繁体   English   中英

Kotlin在使用RxJava2时错误地推断类型为可空性

[英]Kotlin incorrectly inferring type nullability while using RxJava2

我在尝试编写负责发现蓝牙设备的代码时遇到了一个非常令人沮丧的问题。

根据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的条件将突出显示为“始终为true”,并且返回值突然变为Observable<BluetoothDevice?> 这简直令人沮丧,我似乎无法找到解决这个奇怪问题的方法。

这是Android Studio的错误,还是我做错了什么?

这有一个非常简单的解释:RxJava2 支持null值。

使用null会在运行时抛出NullPointerException ,如此处所述: 2.0中有什么不同

在您的特定情况下,IDE会将表达式突出显示为“始终为真”,因为RxJava2运算符不支持可为空的类型,因此它永远不会发出可为null的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM