RxJS Observable de vs de


Es la única diferencia entre Observable.of y Observable.from los argumentos formato? Como el Function.prototype.call y Function.prototype.apply?

Observable.of(1,2,3).subscribe(() => {})
Observable.from([1,2,3]).subscribe(() => {})
Author: Igor, 2017-03-09

3 answers

Es importante notar la diferencia entre of y from cuando se pasa una estructura similar a un array (incluyendo cadenas):

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

Imprimiría toda la matriz a la vez.

Por otro lado,

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

Imprime los elementos 1 por 1.

Para las cadenas el comportamiento es el mismo, pero a nivel de carácter.

 72
Author: Tsvetan Ovedenski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-12 09:19:38

No del todo. Al pasar una matriz a Observable.from, la única diferencia entre ella y Observable.of es la forma en que se pasan los argumentos.

Sin embargo, Observable.from aceptará un argumento que es

Un objeto suscribible, una Promesa, un objeto Observable, un Array, un objeto iterable o similar a un array a convertir

No hay un comportamiento similar para Observable.of, que siempre acepta solo valores y no realiza ninguna conversión.

 48
Author: cartant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-09 21:56:27

Otro hecho interesante es Observable.of ([]) será una matriz vacía cuando se suscriba a ella. Donde como cuando se suscribe a Observable.desde ([]) no obtendrás ningún valor.

Esto es importante cuando se realiza un guardado consecutivo con switchmap. Ex:

.do((data) => {
            this.jobService.save$.next(this.job.id);
        })
        .switchMap(() => this.jobService.addSites(this.job.id, this.sites)
            .flatMap((data) => {
                if (data.length > 0) {
                    // get observables for saving
                    return Observable.forkJoin(jobSiteObservables);
                } else {
                    **return Observable.of([]);**
                }
            })).do((result) => {
            // ..
        })
        .switchMap(() => this.saveComments())
....

If data.length = 0 en la sección addSite, el código anterior está regresando Observable.de ([]) y luego va a guardar comentarios. Pero si lo reemplazas con Observable.de ([]), los métodos siguientes no obtendrán called.

Rxfiddle

 5
Author: Josf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-26 19:53:52