我正在重写库中的方法以利用Rx。下面的代码示例是原始方法。
public void connect(ConnectionListener connectionListener) {
//......
RxBleDevice device = mRxBleClient.getBleDevice(builder.toString());
mEstablishedConnection = device.establishConnection(mContext, false)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(throwable -> {
throwable.printStackTrace();
connectionListener.onFailed();
Log.d(TAG, "Error establishing a connection" + throwable.getMessage());
})
.subscribe(rxBleConnection -> {
mConnection = rxBleConnection;
connectionListener.onConnected();
setNotifications();
Log.d(TAG, "Connection established. Status: " + device.getConnectionState().toString());
}, throwable -> {
if (throwable != null) {
throwable.printStackTrace();
}
});
}
我的第一步是返回Subscription
而不是将其保存到mEstablishedConnection
。这将允许用户取消订阅以触发断开连接:
public Subscription connect() {
//..
RxBleDevice device = mRxBleClient.getBleDevice(builder.toString());
return device.establishConnection(mContext, false)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(throwable -> {
throwable.printStackTrace();
Log.d(TAG, "Error establishing a connection" + throwable.getMessage());
})
.flatMap(rxBleConnection -> {
mConnection = rxBleConnection;
return Observable.empty();
})
.subscribe(o -> {
setNotifications();
Log.d(TAG, "Connection established. Status: " + device.getConnectionState().toString());
}, throwable -> {
if (throwable != null) {
throwable.printStackTrace();
}
});
}
上面的问题是我无法正确地将错误传播回调用者,这样做会很好。如何重写此方法以使其成为被动方式,让调用者收到错误,而不仅仅返回RxBleConnection
,这是第三方类?
答案 0 :(得分:1)
正确答案主要取决于您想要实现的界面。您可以将RxBleConnection
包装在您自己的界面中。
它可能是这样的:
public Observable<YourWrapperClass> connect() {
RxBleDevice device = // ...
return device.establishConnection(context, false)
.doOnNext(connection -> {
setNotifications(connection) // pass the connection to setNotifications()
mConnection = connection // store the mConnection if it is a must - in the reactive approach objects are meant to be passed instead of stored
})
.map(connection -> new YourWrapperClass(connection))
}
此处来电者将负责订阅Observable
(因此可以取消订阅)并且不会知道内部(RxBleConnection
)。