Reputation: 2244
I would have expected it to be printed in order:
The following code can be executed, and I would like to ask whether there are other ways to write
var openLoadingPage$ = Rx.Observable.create(function(observer) {
console.log("open...");
observer.complete();
});
var closeLoadingPage$ = Rx.Observable.create(function(observer) {
console.log("close..");
observer.complete();
});
var ajax$ = Rx.Observable.create(function(observer) {
//todo:get ajax result
observer.next("hello world");
observer.complete();
});
var result$ = Rx.Observable.of(
openLoadingPage$,
ajax$.delay(2000),
closeLoadingPage$)
.concatAll();
result$.subscribe({
next: (value) => {
console.log("get ajax result:", value);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.js"></script>
Upvotes: 0
Views: 309
Reputation: 2962
Beware that when you write Rx.Observable.of(myFunc1())
, myFunc1
is executed right away and its return value (undefined
in your case, because it has none) will be the single event value for the observable.
(same issue with subscribe
, which takes a callback, when you pass the return value of console.log("complete")
)
You're probably going to have more success by writing .subscribe(() => console.log("complete")
) for the last part.
For the func part, it's hard to tell what you're trying to achieve, but here's an attempt:
function myFunc1() {
console.log("myFunc subscribe called");
return "f1"
}
function myFunc2() {
console.log("myFunc2 subscribe called");
return "f2"
}
var myFunc1$ = Rx.Observable.defer(() => Rx.Observable.of(myFunc1()));
var myFunc2$ = Rx.Observable.defer(() => Rx.Observable.of(myFunc2()));
myFunc1$
.delay(2000)
.concat(myFunc2$)
.subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.js"></script>
Upvotes: 1