switchMapTo源可观察发射

时间:2017-12-25 16:16:33

标签: rxjs rxjs5

switchMapswitchMapTo之间的区别在于switchMap会在发射时将每个源发射转换为可观察的,switchMapTo忽略发射值并将每个发射转换为Observable在流创建期间构建。

当您的内部流取决于源流值时,此处的缩略图规则使用switchMap,并且当它没有时使用switchMapTo

但是,如果我不关心排放值,但我确实关心排放时间呢? 意思是我希望根据源Observable发射来评估内部Observable。

这里显而易见的是使用switchMap(() => Observable),但由于我之前提到的拇指规则,它感觉不对。

switchMapTo错误)的示例:



const predefinedKey = 'key';

//This need to be initialized
const obj = {};

function getObservable(key){
  return Rx.Observable.of(obj[key]);
}

//This is initialization stream
const initialize = new Rx.ReplaySubject();
initialize.next(1);

const onInit = initialize.do(val => obj[predefinedKey] = val);

//Would like to access the object only after initialization
const result = onInit.switchMapTo(getObservable(predefinedKey));
//Expect to see 1 in output but see 'undefined' because switchMapTo evaluated before the object is initialized
result.subscribe(val => console.log(val));

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

switchMap)的示例:

&#13;
&#13;
const predefinedKey = 'key';

//This need to be initialized
const obj = {};

function getObservable(key){
  return Rx.Observable.of(obj[key]);
}

//This is initialization stream
const initialize = new Rx.ReplaySubject();
initialize.next(1);

const onInit = initialize.do(val => obj[predefinedKey] = val);

//Would like to access the object only after initialization
const result = onInit.switchMap(() => getObservable(predefinedKey));
//Expect to see 1 in output
result.subscribe(val => console.log(val));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.min.js"></script>
&#13;
&#13;
&#13;

这些例子非常人为,但他们很好地描述了这种情况。

这里的正确方法是什么?我可以用于延迟执行的任何其他Observable函数?

1 个答案:

答案 0 :(得分:3)

根据您的示例,您可以将switchMapToObservable.defer结合使用:

&#13;
&#13;
const predefinedKey = 'key';
const obj = {};

function getObservable(key){
  return Rx.Observable.defer(() => Rx.Observable.of(obj[key]));
}

const initialize = new Rx.ReplaySubject();
initialize.next(1);

const onInit = initialize.do(val => obj[predefinedKey] = val);

const result = onInit.switchMapTo(getObservable(predefinedKey));
result.subscribe(val => console.log(val));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.min.js"></script>
&#13;
&#13;
&#13;

您可以推迟getObservable来电,而不是推迟switchMapTo

const result = onInit.switchMapTo(Rx.Observable.defer(() => getObservable(predefinedKey)));

这取决于具体情况。也就是说,我也不认为使用switchMap有什么问题,而且我个人可能会这样做而不是推迟(这在其他情况下很有用)。