简体   繁体   English

为网络创建自定义 Rxjs Observable

[英]Create Custom Rxjs Observable for network

I'm a beginner with Rxjs, I'm working on a game project have a network implement is:我是 Rxjs 的初学者,我正在做一个游戏项目,有一个网络工具是:

Send by function sendPacket , and server response comes in fuction onReceived通过 function sendPacket发送,服务器响应功能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:我想重构当前的网络结构,如 Angular HttpClient: sendPacket return an Observable我只需要像这样subscribe

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.如果我正确理解您的问题,那么问题在于您的 onReceived 是一个“全局” function ,它与数据包的发送没有直接关联。 In which you need to store the observer for use later where it can be accessed within onReceived.您需要在其中存储观察者以供以后使用,以便在 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.但是,以上假设一次只能有 1 个请求。 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如果您只对发出请求的 Observable 感兴趣,请向下滚动到最后

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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