Search code examples
javascriptangulartypescriptrxjsgetstream-io

Stream.io Chat API - Using Stream Chat with Observables / RxJS in Angular


The Node version of the docs for Stream's Chat API use async/await to connect to the Stream Chat service via the JS client. I have read the RxJS docs on connecting to Websockets, which is what I understand the Stream Chat client is doing under the hood. My question is how I produce Observables from Stream Chat events? For example, from the event object such as this one:

channel.on('message.deleted', event => {
    console.log('event', event);
    console.log('channel.state', channel.state);
});

Thanks for any insight.


Solution

  • If you have a socket like connection you can wrap it with an Observable like this

    function channelObs(channel) {
        return new Observable<any>(
            (subscriber: Observer<any>) => {
                channel.on('eventId', 
                    event => {
                        subscriber.next(event);
                    }
                );
                return () => {// tearDownLogic, i.e. code executed when this Observable is unsubscribed
            }
        );
    }
    

    The Observable returned by the function channelObs can be treated with all operators offered by RxJS