I'm about to mock a http call wrapped into observable. My initial idea was to simply use Observable.of
similar to Promise.resolve
, but it does not seem to work as I expected:
Rx.Observable.of('of1').subscribe(e => console.log(e));
console.log('of2');
Rx.Observable.from(Promise.resolve('from1')).subscribe(e => console.log(e));
console.log('from2');
<script src="https://npmcdn.com/@reactivex/[email protected]/dist/global/Rx.umd.js"></script>
It seems that Observable.of
runs synchronously while Rx.Observable.from(Promise.resolve('from1'))
runs asynchronously (that is what I want). As long as I want to test the spinner is displayed, the synchronous call is not an option for me.
There is some kind of solution when I e.g. delay it or set a timer:
Rx.Observable.of('of1').delay(0).subscribe...
but this also does not look good to me.
How can I turn Observable.of
to run asynchronously? Converting it from Promise seems like an overkill.
If you want an observable of to behave differently you can pass it a scheduler. You could use the async scheduler to make the observable emit values as soon as the call stack is clear. Code wise this would look like this:
Rx.Observable.of(1, 2, 3, Rx.Scheduler.async).subscribe(
(val) => console.log(val)
);
console.log('first');
This will log out:
//first
//1
//2
//3
Working jsbin example here: http://jsbin.com/cunatiweqe/6/edit?js,console
This is because observable.of has by default a null Scheduler. Check the official docs:
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-of
By default, it uses a null IScheduler, which means the next notifications are sent synchronously, although with a different IScheduler it is possible to determine when those notifications will be delivered.
So just import an async Scheduler
import { async } from 'rxjs/scheduler/async';
and send it as the second parameter
Observable.of('of1', async).subscribe(e => console.log(e));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With