Reputation: 69
I'm trying to build messaging system with Observable. My code look like this, pretty simple. But I has slide problem, sometimes method newMessage calls before storageObserver is created, and I'm getting this error
Cannot read property 'next' of null
private storageObserver: any;
public storage: any;
constructor(private auth: AuthenticationService, private http: HttpClient)
{
this.storage = Observable.create(observer => {
this.storageObserver = observer;
});
}
newMessage(message: any) {
this.storageObserver.next(message);
}
Obviously I can check in newMessage like this
newMessage(message: any) {
if(this.storageObserver == null) {
setTimeout(() => {
this.storageObserver.next(message);
}, 500)
} else {
this.storageObserver.next(message);
}
}
But I don't really like this type of hacks. Is any proper way to wait till observer is created?
Upvotes: 1
Views: 96
Reputation: 5944
I suspect you want to be able to 'feed' the observable manually, for as long as you want, but there is another approach to do that.
I prefer to write it like this:
private storageSubject: Subject<any>;
constructor(private auth: AuthenticationService, private http: HttpClient) {
this.storageSubject = new Subject<any>();
this.storage$ = this.storageSubject.asObservable();
}
// This is a public observable that can be subscribed to.
// Do not forget to unsubscribe.
storage$: Observable<any>;
newMessage(message: any) {
this.storageSubject.next(message);
}
Note: If you want the observable to have an initial value, you can use BehaviorSubject<any>
. It will always give the last value immediately after subscribtion, which can be more useful if you want the value to have some form of state.
Upvotes: 2