Lets say we have:
- Array of chat rooms
- Each room has an array of messages
- Rooms and messages in them are changed asynchronously via WebSockets.
The best way to solve it in "Angular2 way" was via ReplaySubject
Delegation: EventEmitter or Observable in Angular2.
Where we have to subscribe for rooms change ChatService.rooms.subscribe(...
, subscribe for message change, then unsubscribe everything...
Isn't it better just to use plain array []
in a Service across Components, and when a new room/message is created just to push that data into array ?
Or maybe i'm doing something wrong.
export class ChatService {
private _rooms: ReplaySubject<Room[]> = new ReplaySubject(1);
rooms: Observable<Room []> = this._rooms.asObservable();
private socket;
private _selectedRoom: ReplaySubject<Room> = new ReplaySubject(1);
selectedRoom: Observable<Room> = this._selectedRoom.asObservable();
constructor(private UserService:UserService) {
this.socket = io.connect(window.location.origin, {
'query': 'token=' + UserService.token
});
this.socket.on('existingRooms', (data) => {
this._rooms.next(data.rooms);
});
}
createNewRoom(string: string) {
this.socket.emit('createNewRoom', {name: string});
this.socket.on('newRoomCreated', (data) => {
this._rooms.first().subscribe((rooms)=> {
rooms.unshift(data)
this._rooms.next(rooms);
}, err => console.error);
});
}
I can't use BehaviorSubject
because i don't have initial value;
I have to call .first()
each time to get current value of ReplaySubject.
I have to subcribe/unsubscribe every component in order to avoid memory leaks.