2017-08-30 36 views
0

我與科爾多瓦的BLE工作(藍牙低功耗)在訂閱運行「回調」函數一次

後,我訂閱BLE(返回可觀察)的通知,我想送一些消息給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當然)

回答

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/[email protected]/bundles/Rx.min.js"></script>