Let me try to explain this in the best way possible.
I have a service that includes an observable class responsible for updating itself. This observable class needs to be pushed out to the app using the observer within the service. How can I trigger that observer from the child without creating a dependency loop?
Here's a simplified example:
class MyService {
subClass$: Observable<SubClass>;
_subClassObserver: Observer<SubClass>;
constructor(private _subClassStore: SubClass){
this.subClass$ = new Observable(observer => {
this._subClassObserver = observer
}).share();
}
pushData(){
this._subClassObserver.next(this._subClassStore)
}
}
class SubClass {
displayData: string;
displayData2: number;
constructor(){
socket.on('setData', function(obj){
this.displayData = obj.dd1;
this.displayData2 = obj.dd2;
//How can I call pushData() in MyService from here to update the app with data?
}
}
}
The _subClassStore is updated through a stream received from socket.io. How can I notify MyService when the SubClass data changes, so it can push it using _subClassObserver.next(_subClassStore)?
UPDATE: I've added more details to the above example to demonstrate their relationship and usage.
SubClass acts as a listener for data streams from socket.io and stores the information in the class. It begins listening upon the construction of MyService.
The objective of MyService is to offer multiple such sub classes that can be subscribed to throughout the app. Each one allows access to a different data stream and its associated data, but all are contained within a single service.
The main question remains how to invoke the pushData() function in the parent to keep the stream updated for subscribers in the app.
Update 2:
This might provide some clarity. Below is how it would be written as a service without the sub class. The reason for not adopting this approach is the need to manage a significant number of these listeners stored to Observables. Abstracting them into classes simplifies the management of information, but I'm struggling with pushing it to the app:
class MyService {
class1$: Observable<DataStream>;
_class1Observer: Observer<DataStream>;
_class1Store: DataStream;
constructor(){
this._class1store = {displayData: 'hello', displayData2: 0};
this.class1$ = new Observable(observer => {
this._class1Observer = observer
}).share();
socket.on('setData', function(obj){
this._class1Store.displayData = obj.dd1;
this._class1Store.displayData2 = obj.dd2;
this._class1Observer.next(this._class1Store)
}
}
interface DataStream = {
displayData: string;
displayData2: number;
}