考虑以下示例:
import { fromEvent } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';
const httpCall$ = ajax.getJSON('https://rickandmortyapi.com/api/character/');
const click$ = fromEvent(document, 'click');
const switchMapExample$ = click$.pipe(
tap(() => console.log('inside switchMap - click happend')),
switchMap(() => {
console.log('inside switchMap - start http request');
return httpCall$.pipe(
tap((val) => console.log('inside switchMap - http response ', val))
);
}
));
switchMapExample$.subscribe((val) => {
console.table(val); // Is There a way to log only the latest value ?
});
通过单击文档内部,它会处理一个新请求。
在这里查看闪电战:rxjs-about-switchmap
使用SwitchMap
允许取消先前的请求。我怎样才能只订阅最新的请求响应?