1

I have 2 services. RoomService -> Returns a list of existing rooms NotificationService -> Returns a Server Sent Event (SSE) when a new room is added.

What I'm trying to do is

  • Fetch all the existing rooms
  • Await the SSE for room creation
  • When SSE is received, add this new room to the list of existing rooms.

Here is what I'm trying to do

export class RoomListComponent {
  rooms$: Observable<Room[]> = this.roomService
    .getRooms()
    .pipe(
      mergeMap((rooms) =>
        this.notificationService
          .getServerSentEvent<Room>()
          .pipe(concatMap((room) => [...rooms, room]))
      )
    );

  constructor(
    private notificationService: NotificationService,
    private roomService: RoomService
  ) {}
}

But this results in error Type 'Observable<Room>' is not assignable to type 'Observable<Room[]>'. Type 'Room' is missing the following properties from type 'Room[]': length, pop, push, concat, and 29 more.ts(2322)

What am I doing wrong?

2
  • sounds like a job for the scan pipe operator to accumulate emissions Commented May 16, 2023 at 14:35
  • 1
    Andrew Allen gave you a nice answer. But if you're intererested why you have this error, it's because you should use map instead of concatMap. ConcatMap would fit, if you returned observable from its lambda. If you're returning simple array you just use map. But it still wouldn't work correctly, as it won't acucmulate all newly added rooms, just the most recent one Commented May 16, 2023 at 15:19

1 Answer 1

2

Using scan to accumulate all new rooms emitted from your notificationService

const initialRooms$ = roomService.getRooms();

const allNewRooms$ = notificationService.getServerSentEvent().pipe(
  scan((acc, curr) => [...acc, curr], []),
  startWith([])
);

// all rooms
combineLatest([initialRooms$, allNewRooms$])
  .pipe(map(([initialRooms, allNewRooms]) => [...initialRooms, ...allNewRooms]))
  .subscribe((arr) => console.log(JSON.stringify(arr)));

Stackblitz

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.