0

Hi I am using angular 7 with rxjs async

in my component I am using ngFor with an async observer

<item-comp [item]="item" *ngFor="let item of groupsService.selectedItems$ | async; ">

</item-comp>

In my service I have an BehaviorSubject that gets emited when a group is selected by the user

  public groupSelected$: BehaviorSubject<any> = new BehaviorSubject(null);

and this is the selectedItems$ Observable :

public selectedItems$ = this.groupSelected$.pipe(
    switchMap((group: any) => {
        if (!group)
          return new EmptyObservable();

        return this.http.get('/api/'+ group)
          .pipe(
            map((res: any) => {
                return res.items;
              }
            )
          )
      }
    )
  )

this works , but now I need to be able to change specific items in response to websocket messages. I have a websocket connection that handles messages where items get updated. is there a way to do this using a reactive approach with rxjs ?

1 Answer 1

1

You can create an higher order functions for websocket updates then chain it up with your http request

const onUpdate=(items)=>updateFromWebSocket.pipe(
   map(itemUpdates=>{........ return updatedItems}
   startWith(items)
)

selectedItems$.pipe(switchMap(items=>onUpdate(items)).subscribe()
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks for your reply. using your solution every time a message arrives from the websocket a new http request will be made ? this seems non efficient, is there a way I can create a new stream that will somehow merge the http results with the websocket updates without making an http request every time ?
The on update is a subsequent stream follow after http request. So it won’t trigger http request. In fact http request will switch to listening socket messages

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.