I've created two functions for testing Observables
that each return an Observable
:
foo() {
return new Observable(observer => {
let i = 0;
setInterval( () => {
if(i === 10) {
observer.complete();
} else {
observer.next(i);
i++;
}
}, 1000);
// If I call observer.complete() here then it never completes
});
}
bar(fooResult) {
return new Observable(observer => {
let j = 0;
setInterval( () => {
if(fooResult) {
observer.next('j -> '+j+' plus fooResult '+JSON.stringify(fooResult));
observer.complete();
} else {
observer.next(j);
j++;
}
}, 2000);
});
}
And make use of them like this:
let fooResult = [];
// Testing observables...
this.exampleProductService.foo().subscribe(
(res) => {
console.log('foo next() -> '+res);
fooResult.push(res);
},
(err) => {
console.error('foo error: '+JSON.stringify(err));
},
() => {
console.log('foo finished');
this.exampleProductService.bar(fooResult).subscribe(
(res) => {
console.log('bar next() -> '+res);
},
(err) => {
console.error('bar error: '+JSON.stringify(err));
},
() => {
console.log('bar finished');
}
);
}
);
Make question(s) are:
Is there a better way to pass data from the completion of an Observable to another function that also returns an Observable? Building up an array seems cumbersome and I can't do the following as the
complete callback
part of theObservable
doesn't pass a parameter likeprogressUpdate
andonError
:(complete) => { this.exampleProductService.bar(complete).// rest of code }
I tried assigning the result of the first function to a variable and then passing that variable but, as expected, I got an Observable and not the result I wanted.
Is there anything incorrect about how I'm doing the above?
Thanks
P.S. This is an Angular 2 application!