Search code examples
typescriptangularobservablerxjsobservers

Angular2 Rxjs observers are not setting if more then one


I'm trying to set multiple observer from my constructor. Only one is getting set and rest of them are not getting as null (unchanged).

I'm not sure why its doing this.

export class gq {

    /**
     * This is observable data service https://coryrylan.com/blog/angular-2-observable-data-services
     */
    constructor(private api: Api)
    {
        this._ = {

            // just to define object here, else it will give error
            observer: {
                s: '', q: '', translation: '', translationLanguage: '', transliteration: '', r: '', content: ''
            },

            // observables
            observable: {
                s$:                 new Observable(observer => this._.observer.s = observer).share(),
                q$:                 new Observable(observer => this._.observer.q = observer).share(),
                translation$:           new Observable(observer => this._.observer.translation = observer).share(),
                translationLanguage$:   new Observable(observer => this._.observer.translationLanguage = observer).share(),
                transliteration$:       new Observable(observer => this._.observer.transliteration = observer).share(),
                r$:               new Observable(observer => this._.observer.r = observer).share(),
                content$:               new Observable(observer => this._.observer.content = observer).share(),
            }
        };


        console.log(this._.observer);
        console.log('triggered constructor');
    }
}

Output comes as

Object {s: Subject, q: "", translation: "", translationLanguage: "", transliteration: ""…}

As you can see it is only setting s with Subject, but rest of them are null


Solution

  • I don't know the rest of your application code but you need to be aware that observables are lazy. This means that the callback you specified when calling the Observable constructor is called only when you subscribe to it.

    Perhaps you only subscribe for the first observable and not for the others...