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

标签 android kotlin rx-java2

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

根据 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/

相关文章:

android - 两个具有相同结构的不同命名表(GreenDAO)

android - 如何在日历中保存选定的项目

android - 哪一个更可取 : Rx-Subject or Android BroadcastReceiver

android - Spek + Retrofit api 测试崩溃

android - 无法使用 gradle 3.0 解析 rxjava2

android - 在 ionic 框架中保存和加载应用程序

android - 使用随机结果设置按钮文本

java - 将 SQLite 数据库备份到外部存储 - 文件引用错误

enums - Kotlin 中的枚举注解

android - 调用 ViewModel 实例会重置 LiveData 吗?