简体   繁体   English

合并为flatMap

[英]Merge implemented as flatMap

Theoretically it should be possible to implement any RxJS operator (except just() and flatMap() ) through flatMap() . 从理论上讲,应该可以通过flatMap()实现任何RxJS运算符( just()flatMap()除外flatMap() For instance map() can be implemented as 例如map()可以实现为

function map(source, selector) {
  return source.flatMap(x => Rx.Observable.just(selector(x)));
}

How to implement merge() through flatMap() ? 如何通过flatMap()实现merge() flatMap() (avoiding mergeAll() too, of course) (当然也避免了mergeAll()

It looks possible if you take advantage of the fact that flatMap can also take array return values. 如果您利用flatMap也可以使用数组返回值的事实,则看起来是有可能的。

Rx.Observable.prototype.merge = function(other) {
  var source = this;
  return Rx.Observable.just([source, other])
           //Flattens the array into observable of observables
           .flatMap(function(arr) { return arr; })
           //Flatten out the observables
           .flatMap(function(x) { return x; });
}

EDIT 1 编辑1

Using RxJS 6 and the pipe syntax 使用RxJS 6和pipe语法

import {of} from 'rxjs'
import {flatMap} from 'rxjs/operators'

function merge (other) {
  return source => of([source, other]).pipe(
           //Flattens the array into observable of observables
           flatMap(arr => arr)
           //Flatten out the observables
           flatMap(x => x)
         );
}

 const {timestamp, map, flatMap, take} = rxjs.operators; const {interval, of: just} = rxjs; const source1 = interval(2000).pipe( timestamp(), map(x => "Interval 1 at " + x.timestamp + " w/ " + x.value) ) const source2 = interval(3000).pipe( timestamp(), map(x => "Interval 2 at " + x.timestamp + " w/ " + x.value) ) function mergeFromFlatMap (other) { return source => just([source, other]).pipe( flatMap(arr => arr), flatMap(seq => seq) ) } source1.pipe( mergeFromFlatMap(source2), take(20) ).subscribe(console.log.bind(console)); 
 <script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM