Reputation: 285
RxJS: On a server in Node.js in the app I'm currently working on I'm trying to determine which would be better: a single stream that handles all outgoing emissions from observables (which get further emitted by socket connections), or dividing my observables into categories. Are there any disadvantages of one way over the other? Let me illustrate what I am trying to ask...
For example: if you were to make a chat application would you set up a single stream and have subscriptions filtered out by chat room such as:
handleEverythingObservable // STREAM OF ALL ROOMS
.filter(obj => obj.chatRoom === joinedChatRoom)
.subscribe(emitToConnectedSocket);
Or would you have an object that divides the streams into categories such as rooms and have multiple separate streams, like:
objectOfObservables = {
room1: room1Observable, // STREAM OF A SINGLE ROOM
room2: room2Observable // STREAM OF A SINGLE ROOM
};
objectOfObservables.room1.subscribe(emitToConnectedSocket);
// NO FILTERING NECESSARY
Are there any design principles that would lead you to choose one way over the other, or would you even do something totally different? Would there be any disadvantages to choose one of these patterns? If a single observable had to handle every single object, it seems that there might be a chance for blocking. I'm thinking that if I divide up the streams, I could terminate them if they were empty, and reopen them when a subscriber was looking for a particular room.
Upvotes: 0
Views: 842
Reputation: 11345
In your use case i would go for centralized observable.
on room join observable are very similar streams, besides the name of the room, not much point to split them up and increase complexity
In case of blocking, either approach the observable you created are supposed to support combine, slicing, delay etc in order to be reused. Whether it will create blocking are normally depends on those small observable segments u will be making e.g forget to retry observable when it fail sliently, or poor error handling etc. You always debug with .do() operator
With approach on you can always create a seperate room stream if you need to
let roomA$=handleEverythingObservable.filter(obj => obj.chatRoom ===joinedChatRoom).filter(obj=>obj.name==='roomA')
In my opinion splitting is easier than combining (likely to run into async/sync issue if not handled well in some case) and allow better flexibility
Upvotes: 1