rxjs,如何将多个主题合并到一个Observable中,但使用不同的方法处理它们

时间:2017-08-18 08:58:57

标签: rxjs rxjs5

我有三个subject。像这样:

const s1$ = new Subject()
const s2$ = new Subject()
const s3$ = new Subject()

这三个主题呼叫next()发出相同的值:const fruit = {id: 1, name: apple};

并且,我有三种方法来处理subjects调用next(fruit)方法的逻辑一对一的对应

method1(): {
  //called when s1$.next(fruit)
}

method2(): {
  //called when s2$.next(fruit)
}

method3(): {
  //called when s3$.next(fruit)
}

我想实现这个:

// here maybe not Observable.merge, it's just a thinking.
Observable.merge(
  s1$,
  s2$,
  s3$
)
.doSomeOperator()
.subscribe(val => {
  //val could be s1$ emit, s2$ emit or s3$ emit
  //but the val is same, the fruit.

  //do some map like s1->method1, s2->method2, s3->method3, so I can omit if...else statement.
  const method = this.method1 | this.method2 | this.method3. 
  method();
})

如何实现这一点,谢谢。

2 个答案:

答案 0 :(得分:0)

Use map operator to add a distinguish sources.

 export class AppComponent  {

      s1(val) {
        console.log('s1', val);
      }

      s2(val) {
        console.log('s2', val);
      }

      constructor() {
        const s1= new Subject();
        const s2= new Subject();
        const m1= s1.map(val=> ({val, source:'s1'}));
        const m2 = s2.map(val=> ({val, source:'s2'}));

        Observable.merge(m1, m2)
        .subscribe(({val, source}) => {
          this[source](val);
        });

        s1.next('apple');
        s2.next('apple');
      }
    }

答案 1 :(得分:0)

如果没有优先级顺序(无论发出哪个Subject,您都希望调用该方法),我建议以下内容:

// here maybe not Observable.merge, it's just a thinking.
Observable.merge(
  s1$.map((val) => ({fn: (arg) => this.method1(arg), val})),
  s2$.map((val) => ({fn: (arg) => this.method2(arg), val})),
  s3$.map((val) => ({fn: (arg) => this.method3(arg), val}))
)
.subscribe({fn, val}=> {
  fn(arg)
});

您也可以在map运算符上执行它们。但是,这取决于您要在此处实现的目标