rxjs icon indicating copy to clipboard operation
rxjs copied to clipboard

rxjs/webSocket should support deserializer return Promise

Open iamcco opened this issue 7 years ago • 6 comments

Feature Request

rxjs/webSock should support deserializer return Promise

Is your feature request related to a problem? Please describe.

import { webSocket } from 'rxjs/webSocket'

const api = (options) => {
  const subject = webSocket(options);
  return {
    subscribe: (params: any) => {
      const observableA = subject.multiplex(
        () => params,
        () => ({ close: true }),
        (message: any) =>  {
          return message.requestId === params.requestId
        }
      );

      return observableA
    }
  }
}

const ws = api({
  url: 'ws://127.0.0.1:50055/ws/v2',
  protocol: 'json',
  binaryType: 'blob',
  deserializer: ({ data }) => {
    return new Promise((res, rej) => {
      const reader = new FileReader()
      reader.readAsText(data)
      reader.onload = () => {
        res(JSON.parse(reader.result))
      }
    })
  }
})

ws.subscribe({requestId: '1', data:{}})
  .subscribe((res) => {
    console.log('res', res);
  })

the deserializer have to return Promise because i have to resolve Blob, but socket.onmessage doesn't support deserializer function to return Promise

iamcco avatar Oct 18 '18 11:10 iamcco

So the goal of this is to do some additional processing to the raw stream data as it arrives?

I think I see the issue, if you have some format that requires you do something asynchronous to deserialize it, you need to do it here, especially if you're multiplexing the socket. 🤔

benlesh avatar Sep 01 '20 22:09 benlesh

(Sorry it took me so long to find this one, BTW) :(

benlesh avatar Sep 01 '20 22:09 benlesh

So the goal of this is to do some additional processing to the raw stream data as it arrives?

I think I see the issue, if you have some format that requires you do something asynchronous to deserialize it, you need to do it here, especially if you're multiplexing the socket. 🤔

Yes 💯

iamcco avatar Sep 02 '20 02:09 iamcco

just to clarify: would this allow us to offload json parsing onto a web worker and away from the main UI thread?

h4de5 avatar Mar 11 '21 17:03 h4de5

@h4de5 you could but that would be pointless. objects are serialised when going between threads even in shared memory buffers.

The point of allowing this function to be a promise is that it allows control to the event loop to be given back. Slower but less blocking.

@benlesh Is this going to be taken on anytime soon? I have very few options when it comes to the synchronous parsing of javascript. reason for async? Breaking up json parsing.

RichardWright avatar Jan 31 '22 14:01 RichardWright

+1 The use case here is I want to encrypt and decrypt the messages using Web Crypto APIs which are unfortunately returning a Promise.

bdbai avatar Aug 31 '24 15:08 bdbai