Converting Listener Api to Promise/Observable

Hi, iam working on an app, where i need to comunicate over UDP. Iam using chrome-sockets-udp for this, but it uses listeners and callbacks, and i want to convert this api into Promise/Observable based API, so I can control it better.

udp sockets works like this:
1)initiate socket
2)add listener
3)send message
4)receive response in listener

My service looks like this:

export class VapsengService {

  socketId:string;

  constructor(private platform:Platform) {
    platform.ready().then(()=>{
      this.initiateUdpSockets().then(()=>{
        this.initiateUdpListener();
      });

    })
   }

  initiateUdpSockets() {
    return new Promise((resolve,reject)=>{
      chrome.sockets.udp.create(socketInfo => {
        console.log(socketInfo);
        this.socketId = socketInfo.socketId;
        chrome.sockets.udp.bind(this.socketId, '0.0.0.0', 4040, (bindresult) => {
          chrome.sockets.udp.setPaused(this.socketId, true);
          resolve(this.socketId)
        });
      });
    })
  }

  initiateUdpListener() {
    chrome.sockets.udp.onReceive.addListener((info) => {
      let result = queryString.parse((window.atob(this.ab2str(info.data))));
      console.log(result);
      this.pauseActiveSocket();
    });
  }

  pauseActiveSocket() {
    chrome.sockets.udp.setPaused(this.socketId, true, () => {
      console.log("Socket paused");
    });
  }


  sendUdpMessage(settings:Settings,code,direction) {
    const dataToSend = { };
    let arrayBuffer = this.str2ab(window.btoa((queryString.stringify(dataToSend))));
    return new Promise((resolve,reject)=>{
      chrome.sockets.udp.setPaused(this.socketId, false, () => {
        try{
          chrome.sockets.udp.send(this.socketId, arrayBuffer, "192.168.5.26", 4040, function (sendInfo) {
            resolve();
          });
        }
        catch(e){
          console.log(e);
          reject();
        }
      });
    })
  }

  str2ab(str) {
    var buf = new ArrayBuffer(str.length);
    var bufView = new Uint8Array(buf);
    for (var i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
     return buf; 
  }

  ab2str(buf) {
    return String.fromCharCode.apply(null, new Uint8Array(buf));
  }
}

The problem is, how can i make promise out of the initiateUdpListener method? Another solution that comes to my mind, was, that i can create subject and just emit value when listener is triggered, but it seems like a overkill. Any ideas how to solve this?

I think that’s a fantastic idea, and that’s how I would do it. Just call next with your result on that Subject where you currently have the console.log.

I did it like that and it works great.

1 Like