Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS Observable returns data immediately, why?

In my current project I've found the function given below:

translateString(stringToTranslate: string) {
    let translation;
    this.translateService.get(stringToTranslate).subscribe(
        data => {
            translation = data;
        });
    return translation;
}

It looks ridiculous since TranslateService.get() method returns an Observable in every case, but it actually works somehow (the translated string is returned immediately)... What is the explanation of this behavior? Shouldn't callback function be added to the execution stack and run later?

like image 295
Daniel Kucal Avatar asked Mar 21 '17 13:03

Daniel Kucal


1 Answers

The fact you're using Observables doesn't automatically mean that everything is going to be called in a separate JavaScript callback.

In fact most of the default Observables and operators emit everything immediately and don't use any Scheduler by default. For example have a look at this https://github.com/ReactiveX/rxjs/blob/master/src/observable/ArrayObservable.ts#L118

This is obviously different when using for example the delay() operator which needs to schedule execution, see https://github.com/ReactiveX/rxjs/blob/master/src/operator/delay.ts#L52.

For example consider the following example:

Observable.from([1,2,3], Scheduler.async)
  .subscribe(val => console.log(val));

Observable.from(['a','b','c'], Scheduler.async)
  .subscribe(val => console.log(val));

Which schedules each emission into another JS callback:

1
"a"
2
"b"
3
"c"

See demo: https://jsbin.com/zalugev/3/edit?js,console

If you don't set any scheduler everything will be emitted immediately (synchronously):

Observable.from([1,2,3])
  .subscribe(val => console.log(val));

Observable.from(['a','b','c'])
  .subscribe(val => console.log(val));

Which prints the following:

1
2
3
"a"
"b"
"c"

See demo: https://jsbin.com/zalugev/4/edit?js,console

Regarding your question, you shouldn't rely on the 3rd party library to emit values immediately because you never know when this changes and your code will break.

like image 138
martin Avatar answered Nov 14 '22 22:11

martin