我是RxJava和RxAndroidBle的新手,希望能为我要解决的问题提供帮助。本质上,我有一个BLE设备,该设备具有四个特征。这些可观察对象发出的数据被合并为一个可观察对象:
private RxBleDevice mBleDevice;
private Disposable mConnectionSubscription;
...
mConnectionSubscription = mBleDevice.establishConnection(false)
.flatMap(rxBleConnection -> Observable.combineLatest(
rxBleConnection.setupNotification(UUID.fromString(CHARACTERISTIC_UUID0)).flatMap(observable -> observable),
rxBleConnection.setupNotification(UUID.fromString(CHARACTERISTIC_UUID1)).flatMap(observable -> observable),
rxBleConnection.setupNotification(UUID.fromString(CHARACTERISTIC_UUID2)).flatMap(observable -> observable),
rxBleConnection.setupNotification(UUID.fromString(CHARACTERISTIC_UUID3)).flatMap(observable -> observable),
MyDataClass::new
))
.observeOn(AndroidSchedulers.mainThread())
.doFinally(this::disconnect)
.subscribe(
myData -> {
this.onNotificationReceived(myData);
},
this::onNotificationSetupFailure
);
其中:
public class MyDataClass<Data0, Data1, Data2, Data3> {
...
public MyDataClass(Data0 data0, Data1 data1, Data2 data2, Data3 data3) {
...
}
}
以上工作正常。我试图做的是订阅另一个特征。但是,这只会偶尔发出数据。因此,我想将此额外的Observable连接到单独的观察者(例如onNotificationReceived2
)。我不希望这些额外的可观察数据与MyDataClass
相关。我该怎么办?
答案 0 :(得分:0)
在您的mydf %>%
set_names(paste0("V", seq_along(.))) %>%
mutate(V4 = abs(V2 - as.numeric(V1)))
之前,插入:
flatMap()
然后使用.doOnNext( rxBleConnection -> savedConnection = rxBleConnection )
设置您的其他订阅。
当您处置(或丢失)原始连接时,请不要忘记将savedConnection
设为空。
答案 1 :(得分:0)
我找到了我想要的解决方案。根据{{3}}和罗伯特·刘易斯的评论,我最终做了以下事情:
private RxBleDevice mBleDevice;
private Disposable mConnectionSubscription1;
private Disposable mConnectionSubscription2;
...
Observable<RxBleConnection> sharedConnectionObservable = mBleDevice.establishConnection(false)
.replay(1).refCount();
mConnectionSubscription1 = sharedConnectionObservable
.flatMap(rxBleConnection -> Observable.combineLatest(
rxBleConnection.setupNotification(UUID.fromString(CHARACTERISTIC_UUID0)).flatMap(observable -> observable),
rxBleConnection.setupNotification(UUID.fromString(CHARACTERISTIC_UUID1)).flatMap(observable -> observable),
rxBleConnection.setupNotification(UUID.fromString(CHARACTERISTIC_UUID2)).flatMap(observable -> observable),
rxBleConnection.setupNotification(UUID.fromString(CHARACTERISTIC_UUID3)).flatMap(observable -> observable),
MyDataClass::new
))
.observeOn(AndroidSchedulers.mainThread())
.doFinally(this::disconnect)
.subscribe(
myData -> {
this.onNotificationReceived(myData);
},
this::onNotificationSetupFailure
);
mConnectionSubscription2 = sharedConnectionObservable
.flatMap(rxBleConnection -> rxBleConnection.setupNotification(UUID.fromString(CHARACTERISTIC_UUID4)).flatMap(observable -> observable))
.observeOn(AndroidSchedulers.mainThread())
.doFinally(this::disconnect)
.subscribe(
myData2 -> {
this.onNotificationReceived2(myData2);
},
this::onNotificationSetupFailure
);