在订阅时运行"回调"功能一次

时间:2017-08-30 12:14:51

标签: ionic-framework rxjs

我正在使用cordova的BLE(蓝牙低功耗)

在我订阅了BLE(返回Observable)的通知后,我想向ble设备发送一些消息,执行此操作的最佳方法是什么,基本上我需要在订阅后运行一次函数一旦设备回复我,订阅中的代码就会运行。

ble.startNotification(deviceId, uuid1, uuid2).subscribe(bufferData=> {
   //do something with bufferData
})

现在在此之后,我想运行类似回调的东西,

.then(()=> {
  //send message to device (only once), after the message is sent, the device will respond back and the `do something with bufferData` code will be run
})

我可以轻松地执行setTimeout并在几秒钟后向设备发送消息,当然它可以正常工作,但我想在我确定订阅发生之后干净利落地完成(订阅)当然是观察到的)

1 个答案:

答案 0 :(得分:1)

您可以使用create operator包装现有方法,并添加将在每个新订阅上执行的自定义代码。

参见示例:



// emulate cordova with "dummy" bluetooth interface
const BLE = {
 startNotification: () => Rx.Observable.interval(1000)
}

const wrappedBLE = (...params) => 
  Rx.Observable.create(observer => {
    // constructor fn will be executed on every new subscribtion

    const disposable = BLE.startNotification(...params).subscribe(observer);

    // place code to send notification here, instead of console log
    console.log('New subscriber for BLE with params: ', params);  

    return disposable;
  });


wrappedBLE("param1", "param2", "param3")
  .subscribe(e => console.log("received notification: ", e));

<script src="https://unpkg.com/rxjs@5.4.3/bundles/Rx.min.js"></script>
&#13;
&#13;
&#13;