RxJS Observable returns data immediately, why?

In my current project, I found the function below:

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

This looks ridiculous, because the TranslateService.get () method returns an Observable in each case, but it really works somehow (the translated string returned immediately) ... What is the explanation for this behavior? Should I add a callback function to the execution stack and run later?

+4
source share
4 answers

The fact that you use Observables does not automatically mean that everything will be called in a separate JavaScript callback.

Observables - . , https://github.com/ReactiveX/rxjs/blob/master/src/observable/ArrayObservable.ts#L118

, , , , delay(), , . https://github.com/ReactiveX/rxjs/blob/master/src/operator/delay.ts#L52.

, :

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

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

JS:

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

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

- , ():

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

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

:

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

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

, , , , , .

+7

, , . , Observable.of, . translateService , translation.

, , , , rxjs. https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md, Schedulers Renamed

+1

An Observable - onSuccess(), onError() onComplete(). , Observable . Observable ( ):

export class Observable {
  constructor(subscribe) {}
  subscribe(observerOrNext, error, complete) {} // callbacks
}
Observable.create = (subscribe) => {
    return new Observable(subscribe); // dot-chaining
}

, AndrΓ© Staltz .

+1

translateString - , return translation . , , this.translateService.get(stringToTranslate) return.

return translation, . , flatMap, this.translateService.get(stringToTranslate).

subscribe , , //.

....subscribe(
    data => //success data,
    error => //error data,
    completed => //observable completed
);
0

Source: https://habr.com/ru/post/1672827/


All Articles