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?
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.
Not sure if that could be the issue here, but some observables emit synchronously. This is the case of Observable.of for example I believe. If translateService is synchronous, you would then immediately get your subscription observer called and your translation value filled.
You can influence the timing of the emission by using schedulers, which is probably the less documented part of rxjs. Have a look at https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md, section Schedulers Renamed
An Observable is essentially just a wrapper for onSuccess(), onError() and onComplete() callbacks. If functions that are executed are synchronous an Observable will be too. This is core functionality of an Observable (the rest is just cleanup):
export class Observable {
constructor(subscribe) {}
subscribe(observerOrNext, error, complete) {} // callbacks
}
Observable.create = (subscribe) => {
return new Observable(subscribe); // dot-chaining
}
Watch this video where André Staltz constructs observable from scratch.