Meqwz
Meqwz

Reputation: 1491

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.

Upvotes: 0

Views: 568

Answers (2)

Picci
Picci

Reputation: 17762

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

Upvotes: 0

Shashank Vivek
Shashank Vivek

Reputation: 17514

You need create a Subject and subscribe it as follows

chat.service.ts

private chatEventListener = new Subject<any>();

bindEvents(){
   channel.on('message.deleted', event => {
    const eventObj = {
       event : event,
       state : channel.state
    };
    this.chatEventListener.next(eventObj );
  });
}

subscribeToNotifications(){
  this.chatEventListener.asObservable();
}

in component.ts

this.chatService.subscribeToNotifications().subscribe(event => {
   console.log(event);
})

Upvotes: 0

Related Questions