Skip to content
Advertisement

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

JavaScript

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

JavaScript

How can I implement this idea? Thank you so much

Advertisement

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement