简体   繁体   中英

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

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.

there are answers in this article, it's for absolute beginners so you should catch everything.

if you are interesting only in Observable that makes request, scroll down to the end

https://justeugen.medium.com/rxjs-for-beginners-1-c87f92f4a9d2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM