Let's say I have a Chat, I load messages from Rest and then I listen fron new messages from WebSocket.
I also need the ability to clear all messages. Here is the simplified HTML template:
<div *ngFor="let message of messages$ | async"> {{message}} </div>
<button (click)="clearChat">Clear Chat </button>
and the simplified component code:
public messages$: Observable<string[]>;
private clearChatSubject = new BehaviorSubject<boolean>(false);
ngOnInit() {
const initialMessages$: Observable<string[]> = this.chatRestService.getMessages$(this._chatRoomId);
const newMessages$: Observable<string[]> = this.chatSocketService.getMessageEvents$(this._chatRoomId).pipe(
startWith([])
);
this.messages$ = initialMessages$.pipe(
concatMap(initialMessages => {
return this.clearChatSubject.asObservable().pipe(map(reset => reset ? [] : initialMessages))
}),
switchMap(initialMessages => {
return newMessages$.pipe(
map(newMessages => initialMessages.concat(newMessages)),
tap(mergedMessages => initialMessages = mergedMessages)
)
})
);
}
public clearChat() {
this.clearChatSubject.next(true);
}
is this the best approach? Is there a better way? I find it a bit wired to have a clearChatSubject that can be true or false.
also the part where I merge the messages from rest and WebSockets feels wired to me.
Thank you