我目前正在使用 Kotlin 开发一个 android 应用程序。这是我第一次使用这种编程语言,我目前正在努力将 Java 代码示例翻译成 Kotlin。
我想在 Kotlin 中实现这个问题的答案。
我当前的实现无法编译,因为 Ovservable::from 方法似乎已被删除。
这是我目前的方法:
connectionObservable!!.flatMap { connection ->
connection.discoverServices()
.flatMap { services ->
services.getService(UUID.fromString("My UUID")).map(BluetoothGattService::getCharacteristics)
//here occurs the error, he wants a Single Source but got a observable with the ble characteristic
.flatMap { characteristics: MutableList<BluetoothGattCharacteristic> -> Observable.fromIterable(characteristics) }
.flatMap { characteristic: BluetoothGattCharacteristic ->
connection.setupNotification(characteristic)
.flatMap { observable: Observable<ByteArray> -> observable ,Pair<BluetoothGattCharacteristic, ByteArray>(characteristic, observable)}
}
}
}.subscribe { pair: Pair<BluetoothGattCharacteristic, ByteArray> ->
genericModel[pair.first.uuid] = pair.second
throwable -> { /* handle errors */ }
}
你能指出我的错误以便我理解我做错了什么吗?
提前致谢!乔纳斯
您的代码有几个潜在的问题。
.flatMap { observable: Observable<ByteArray> -> observable ,Pair<BluetoothGattCharacteristic, ByteArray>(characteristic, observable)}
我想你可能想flatMap
的observable: Observable<ByteArray>
(类型由我为清楚起见加)从它那里得到ByteArray
的对象。这看起来像这样:
.flatMap { observable: Observable<ByteArray> -> observable.map { bytes -> Pair(characteristic, bytes) }}
Observable
从期望 a 的 lambda返回a 时,代码将无法编译SingleSource
——正如您的编译器所说的那样。如果你有 aSingle
并且你愿意.flatMap
- 它的 lambda 应该返回另一个SingleSource
。有一个.flatMapObservable
函数期望ObservableSource
您应该使用哪个函数。最终结果将如下所示: connectionObservable!!.flatMap { connection ->
connection.discoverServices()
.flatMapObservable { services ->
services.getService(UUID.fromString("My UUID")).map(BluetoothGattService::getCharacteristics)
//here occurs the error, he wants a Single Source but got a observable with the ble characteristic
.flatMapObservable { characteristics: MutableList<BluetoothGattCharacteristic> -> Observable.fromIterable(characteristics) }
.flatMap { characteristic: BluetoothGattCharacteristic ->
connection.setupNotification(characteristic)
.flatMap { observable: Observable<ByteArray> -> observable.map { bytes -> Pair(characteristic, bytes) }}
}
}
}.subscribe { pair: Pair<BluetoothGattCharacteristic, ByteArray> ->
genericModel[pair.first.uuid] = pair.second
throwable -> { /* handle errors */ }
}
Observable.fromIterable()
仍然是Observable
. 您可能没有使用Observable
正确包中的类。Observable
包中有一个类,java.util
但我们在这里使用的是一个RxJava 2
有包的类io.reactivex
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句