您好,我正在尝试学习 RxAndroidBLE 并阅读单个特征 使用以下代码:
String macAddress = "84:CC:A8:2E:24:6A";
RxBleDevice device = rxBleClient.getBleDevice(macAddress);
Disposable disposable = device.establishConnection(false) // <-- autoConnect flag
.subscribe(
rxBleConnection -> {
// All GATT operations are done through the rxBleConnection.
// Toast.makeText(MainActivity.this, "connected" , Toast.LENGTH_LONG).show();
},
throwable -> {
// Handle an error here.
Toast.makeText(MainActivity.this, "connect error" + throwable.getMessage(), Toast.LENGTH_LONG).show();
}
);
// When done... dispose and forget about connection teardown :)
disposable.dispose();
// Read characteristic
device.establishConnection(false)
.flatMapSingle(rxBleConnection -> rxBleConnection.readCharacteristic(UUID.fromString(PIN_UUID))
// .observeOn(AndroidSchedulers.mainThread())
.subscribe(
characteristicValue -> {
// Read characteristic value.
rtext.setText(new String(characteristicValue));
},
throwable -> {
Toast.makeText(MainActivity.this, "read error" + throwable.getMessage(), Toast.LENGTH_LONG).show();
// Handle an error here.
}
));
这给出了错误:
.flatMapSingle(rxBleConnection -> rxBleConnection.readCharacteristic(UUID.fromString(PIN_UUID))
^
(argument mismatch; bad return type in lambda expression
Disposable cannot be converted to SingleSource<? extends R>)
其中 R,T 是类型变量: R extends Object 在方法 flatMapSingle(Function super T,? extends SingleSource extends R>>) 中声明 T 扩展 Observable 类中声明的对象
我尝试使用 .flatMap 和 .flatMapSingle,但都给出了相同的错误。 我也想知道我是否取消注释该行: .observeOn(AndroidSchedulers.mainThread())
AndroidSchedulers 未定义且导入行不存在: 导入 io.reactivex.android.schedulers.AndroidSchedulers;
答案 0 :(得分:0)
显然你把括号放错了地方。以 .flatMapSingle
开头的行在代码段末尾关闭。
device.establishConnection(false)
// [Answer] The line below should be closed but instead the closing bracket is ...
.flatMapSingle(rxBleConnection -> rxBleConnection.readCharacteristic(UUID.fromString(PIN_UUID))
// .observeOn(AndroidSchedulers.mainThread())
.subscribe(
characteristicValue -> {
// Read characteristic value.
rtext.setText(new String(characteristicValue));
},
throwable -> {
Toast.makeText(MainActivity.this, "read error" + throwable.getMessage(), Toast.LENGTH_LONG).show();
// Handle an error here.
}
// [Answer] ... is closed below! Thus you try to return a Disposable where a Single is expected
));
尝试使用以下内容:
device.establishConnection(false)
.flatMapSingle(rxBleConnection -> rxBleConnection.readCharacteristic(UUID.fromString(PIN_UUID)))
// .observeOn(AndroidSchedulers.mainThread())
.subscribe(
characteristicValue -> {
// Read characteristic value.
rtext.setText(new String(characteristicValue));
},
throwable -> {
Toast.makeText(MainActivity.this, "read error" + throwable.getMessage(), Toast.LENGTH_LONG).show();
// Handle an error here.
}
);