【问题标题】:On subscription run a "callback" function once订阅时运行一次“回调”函数
【发布时间】:2017-08-30 12:14:50
【问题描述】:

我正在使用 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 并在几秒钟后向设备发送一条消息,当然它可以工作,但我想干净地做到这一点,在我确定订阅发生之后(订阅 Observable当然)

【问题讨论】:

    标签: ionic-framework rxjs


    【解决方案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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 2019-04-12
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      相关资源
      最近更新 更多