Reputation: 2077
I have a http service that I need to call depending on the users input.
saveImage(): Observable<Photo> {
if (!this.squaredImage) {
return Observable.of();
}
this.photoCreateDto = {
sourcePhoto: this.sourceImage,
squaredPhoto: this.squaredImage,
fileExtension: this.fileExtension
};
return this.photoService.createPhoto(this.photoCreateDto);
}
I call saveImage
from another save function:
save() {
this.saveImage().subscribe((newPhoto: Photo) => {
.. never gets here
});
}
If this.squaredImage
has no value and the empty promise is returned, the chain ends. If the createPhoto
service is called, it continues. I have also tried returning Observable.empty()
. How do you handle this scenario in rxjs?
Upvotes: 3
Views: 1457
Reputation: 96959
The problem is that you're handling only the next
notifications with:
this.saveImage().subscribe((newPhoto: Photo) => { ... });
... while Observable.of()
or Observable.empty()
don't emit any next
(they just send complete
notifications).
So one thing you can do is to emit for example null
and then in the subscriber check what value you sent:
saveImage(): Observable<Photo> {
if (!this.squaredImage) {
return Observable.of(null);
}
...
}
...
this.saveImage().subscribe((newPhoto: Photo) => {
if (newPhoto === null) {
// ...
}
// ...
})
Or you can listen to both next
and complete
notifications (but be aware that when you return this.photoService.createPhoto
a complete
notification is probably sent as well):
this.saveImage().subscribe({
next: (newPhoto: Photo) => {...}
complete: () => { ... }
})
Upvotes: 5