1

I noticed in my angular app that rxjs operators, like switchMap, map etc, were not working. (My IDE also gives a hint about that.) To be sure, I ran the following code. If I replace switchMap with subscribe, I do see 'value returned' in the console.

Any idea why the operators are not working?

import { Component, OnInit } from '@angular/core';
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/switchMap';

@Component({
    selector: 'page-2',
    template: `
    <h2>{{title}}</h2>
    `,
})
export class Page2Component implements OnInit{
    title = 'Page2';

    ngOnInit() {
        let obs = new Observable(observable  => {
            observable.next('value returned');
        });
        obs.switchMap(console.log);
    }
}

1 Answer 1

2

In order to "fire" an observable you need to subscribe to it. Otherwise they will stay "cold".

The Subscribe operator is the glue that connects an observer to an Observable. In order for an observer to see the items being emitted by an Observable, or to receive error or completed notifications from the Observable, it must first subscribe to that Observable with this operator.

An Observable is called a “cold” Observable if it does not begin to emit items until an observer has subscribed to it; an Observable is called a “hot” Observable if it may begin emitting items at any time, and a subscriber may begin observing the sequence of emitted items at some point after its commencement, missing out on any items emitted previously to the time of the subscription.

Ref: http://reactivex.io/documentation/operators/subscribe.html

Sign up to request clarification or add additional context in comments.

5 Comments

You don't necessarily need to call subscribe to emit values when you call any of the operators like switchMap. reactivex.io/rxjs/class/es6/…
@Naveed As I've said in my answer if you don't subscribe to an observable, it will stay cold, it won't have a connection with its observer. Hence, you won't be able to "observe" anything. Check the example in the link you have given. I admit using emit in that documentation is a bit confusing but switchMap just maps/emits these values to observables but if these observables don't have observers, you can't see/observe anything.
Ok. I got that. switchMap and map return another observable that I need to subscribe to.
e.g. Following worked for me: let obs = new Observable(observable => { observable.next('value returned'); }); let obs2 = obs.map((value) => `${value} mapped!`); obs2.subscribe(console.log);
@Naveed Glad you figured it out :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.