Tom Sawyer
Tom Sawyer

Reputation: 857

How to use Observable.If without calling functions

Currently, functions isEven and isOdd are called for each IF. Is there a way that the functions are called only when the evaluation of the IF correspond to the logic path of the function?

Example: reference of JSBin: http://jsbin.com/wegesaweti/1/edit?html,js,output)

var isEven = function(x) {
  console.log('function isEven called')
  return Rx.Observable.return(x + ' is even');
};    
var isOdd = function(x) {
  console.log('function isOdd called')
  return Rx.Observable.return(x + ' is odd');
};
var source = Rx.Observable.range(1,4)
  .flatMap((x) => Rx.Observable.if(
    function() { return x % 2; },
    isOdd(x),
    isEven(x)
));    
var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    });

Current output:

function isOdd called
function isEven called
Next: 1 is odd
function isOdd called
function isEven called
Next: 2 is even
function isOdd called
function isEven called
Next: 3 is odd
function isOdd called
function isEven called
Next: 4 is even

Expected output

function isOdd called
Next: 1 is odd
function isEven called
Next: 2 is even
function isOdd called
Next: 3 is odd
function isEven called
Next: 4 is even

Thank you!

Upvotes: 0

Views: 70

Answers (1)

user3682091
user3682091

Reputation: 755

Base on the RXJS docuemntation the thenSource and elseSource need to be Observable (or Scheduler for elseSource).

An alternative for your problem:

var source = Rx.Observable.range(1,4).flatMap((x) => 
    (x % 2) == 1 ? isOdd(x) : isEven(x)
);

Working example: http://jsbin.com/godubemano/1/edit?html,js,output

Upvotes: 1

Related Questions