Skip to content

Create Custom Rxjs Observable for network

I’m a beginner with Rxjs, I’m working on a game project have a network implement is:

Send by function sendPacket, and server response comes in fuction onReceived

sendPacket: function(packet) {
  this._tcpClient.sendToServer(packet);
}
onReceived: function (pkg) {
}

I want to refactor the current network struct like Angular HttpClient: sendPacket return an Observable and I just need subscribe like this:

network.sendPacket(myPacket).subscribe(response => ...)

How can I implement this idea? Thank you so much

Answer

If I understand your issue correctly, the problem is that your onReceived is a “global” function that isn’t directly associated with the sending of the packet. In which you need to store the observer for use later where it can be accessed within onReceived. Something like:

let savedObserver = null;

sendPacket: function(packet) {
  return new Observable(observer => {
    this._tcpClient.sendToServer(packet);
    savedObserver = observer;
  })
}

onReceived: function (pkg) {
  if (savedObserver) {
    savedObserver.next(pkg);
    savedObserver.complete();
    savedObserver = null;
  }
}

However, the above assumes there can only ever be 1 request at a time. To allow for multiple parallel requests you need to store an observable per request, then be able to link the response to the request and find the correct observable.