RxJS5与延迟可观察的组合的高级示例

时间:2017-01-19 11:10:15

标签: javascript functional-programming rxjs rxjs5

Hy,我遇到了RxJS组合操作员的问题......

这是示例对象:

const userData = {
        dbKeyPath: 'www.example.com/getDbKey',
        users:[
            {name:'name1'},
            {name:'name2'},
            {name:'name3'}
        ]
    }

从他们那里观察:

const userDataStream  = Rx.Observable.of(userData)
const dbKeyStream : string = this.userDataStream.mergeMap(_userData => getDbKey(_userData.dbKeyPath))
const userStream = this.userDataStream.pluck('users').mergeMap(_users=>Rx.Observable.from(_users))

我的预期结果是具有组合可观察量的流:

[user[0],dbKey],[user[1],dbKey],[user[2],dbKey]... 

withLatestFrom运算符一起运行良好:

const result = userStream.withLatestFrom(dbKeyStream) // [user, dbkey]

但是,当我将.delay()运算符应用于dbKeyStream时,如何归档相同的结果?

1 个答案:

答案 0 :(得分:1)

我建议使用mergeMap overload with the selectorFunc



const userData = {
        dbKeyPath: 'www.example.com/getDbKey',
        users:[
            {name:'name1'},
            {name:'name2'},
            {name:'name3'}
        ]
    };

function getDbKey(path) {
  return Rx.Observable.of('the-db-key:'+path)
    .do(() => console.log('fetching db key for path: '+ path))
    .delay(1000);
}

const userDataStream  = Rx.Observable.of(userData)
  .mergeMap(
    _userData => getDbKey(_userData.dbKeyPath),
    (_userData, dbKey) => _userData.users.map(_usr => ({ user: _usr, dbKey }))
  )
.subscribe(console.log);

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.3/Rx.js"></script>
&#13;
&#13;
&#13;

这使您可以根据需要将输入对象和每个输出值组合在一起。