SamuraiJack
SamuraiJack

Reputation: 5569

How to return observable of values emitted by inner observable?

I am trying to return observable of whatever is the response of inner observable.

FIDDLE

  function Resolver() {
var x="5";

 var ob1= Rx.Observable.of(1).delay(2000);

 ob1.subscribe(d=>{
    if(d=='something'){
     x=x*10;
    }
    else{
    x=x*20;
    }
     console.log(x);
  });

 return Rx.Observable.of(
  x
  );
}
console.clear();
var mydata= Resolver().subscribe(data => {
 console.log(data)
});

The above code returns 5 first and 100 later. I just want to return 100.

Upvotes: 0

Views: 556

Answers (2)

martin
martin

Reputation: 96979

You should rather use map operator instead of subscribing.

import { map } from 'rxjs/operators';

function Resolver() {
  ...
  return ob1.pipe(map(d=>{
    if(d == 'something') {
      return x * 10;
    } else {
      return x * 20;
    }
  }));
}

Upvotes: 2

Tim H
Tim H

Reputation: 75

You should take a look at the map operator since I don't see your need for an inner observable. In case of an inner observable you can use the switchMap operator, this maps the inner observable result to the outer observable. For instance:

function Resolver() {
  var x=5;

  return Rx.Observable.of(1).delay(2000).pipe(
    map(data => {
      if(d=='something'){
        x=x*10;
      }
      else{
        x=x*20;
      }
      return x;
    });
  );
}

Upvotes: 0

Related Questions