0

Now my program which uses cluster lib looks like this:

if(cluster.isMaster) {
  // here goes Rx subscriptions and workflows for the Master
} else if (cluster.isWorker){
 // here goes Rx subscriptions and workflows for a Worker
}

It's looks a little bit ugly and I need to duplicate some code which is common for both Master and Worker. Is there a way to rewrite it in more "reactive" style?

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
kharandziuk
  • 12,020
  • 17
  • 63
  • 121

1 Answers1

1

It's a good practice to break down your logic into "tasks" or re-usable transformations. You can then combine them together to make more complex pipelines of data transformations, customised for different situations.

function masterTransform( data$ ){
    return data$.map( extractData )
             .map( doSomething("master"))
             .map( anotherThing )
             .distinctUntilChanged()
             .scan( (a,b) => a + b, 0 );
}

function slaveTransform( data$ ){
    return data$.map( extractData )
             .map( doSomething("slave"))
             .flatMapLatest( combineOtherSource )
             .scan( (a,b) => Math.max(a,b), 0 );
}


let stream$ = cluster.isMaster 
               ? service.getMasterData().let( masterTransform )
               : service.getSlaveData().let( slaveTransform );

stream$.subscribe( data => console.log( data ));
Peter Hall
  • 53,120
  • 14
  • 139
  • 204