Within my application, I am utilizing a RxJS subject to broadcast changes within a collection. Each time the collection is updated, the subject emits the new contents as an array format.
let collectionSubject = new Rx.BehaviourSubject();
collectionSubject.onNext([{
id: 1
}]);
The goal is to allow client code to subscribe to this collection based on a specific 'id'. For instance, upon any alterations in the collection, they should only receive the item that corresponds to the queried id, if it exists. Otherwise, they should get undefined.
An initial approach to accomplish this could be:
byId(id) {
return collectionSubject.filter(items => items.find(item => item.id == id));
}
Yet, this method creates a fresh observable each time and leads to numerous unnecessary iterations of the items array. One potential improvement would involve using a Map with id keys to cache observables. However, this still necessitates multiple iterations of the items array for various ids.
It appears that the most effective solution entails crafting intricate mechanisms to generate, retain, and terminate subjects for each id, conduct a single iteration of the collection during modifications, and dispatch every item to its relevant subject.
Is there a more straightforward and conventional way to achieve this by leveraging the inherent RxJS operators? The primary emphasis is on iterating through the underlying collection just once.