最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using combineLatestWith with multiple stream values? - Stack Overflow

programmeradmin3浏览0评论

RxJS bineLatest is deprecated and replaced with bineLatestWith.

How do we use it when we have 3 or more streams to bine?

I've developed this example for what I thought would work.

const hello$: Observable<string> = of('hello').pipe(
  bineLatestWith(of('world')),
  bineLatestWith(of('!')),
  map((arr) => {
    const greeting = arr[0];
    const subject = arr[1];
    const punctuation = arr[2];
    return greeting + ' - ' + subject + punctuation;
  })
);

And this is the Stackblitz

Thoughts?

RxJS bineLatest is deprecated and replaced with bineLatestWith.

How do we use it when we have 3 or more streams to bine?

I've developed this example for what I thought would work.

const hello$: Observable<string> = of('hello').pipe(
  bineLatestWith(of('world')),
  bineLatestWith(of('!')),
  map((arr) => {
    const greeting = arr[0];
    const subject = arr[1];
    const punctuation = arr[2];
    return greeting + ' - ' + subject + punctuation;
  })
);

And this is the Stackblitz

Thoughts?

Share asked Oct 25, 2022 at 19:49 OleOle 47.5k70 gold badges238 silver badges445 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

bineLatestWith joins the observable with the given one in an array (say cons). Imagine it like so:

  1. "hello" => "world" = ["hello", "world"]
  2. ["hello", "world"] => "!" = [["hello", "world"], "!"]

so arr bees [["hello", "world"], "!"] where => is bineLatestWith

const hello$: Observable<string> = of('hello').pipe(
  bineLatestWith(of('world')),
  bineLatestWith(of('!')),
  map((arr) => {
    const first = arr[0];
    const greeting = first[0]
    const subject = first[1];
    const punctuation = arr[1];
    return greeting + ' - ' + subject + punctuation;
  })
);

From docs: Create an observable that bines the latest values from all passed observables and the source into arrays and emits them.

The code can look nicer with destructuring, like so:

const hello$: Observable<string> = of('hello').pipe(
  bineLatestWith(of('world')),
  bineLatestWith(of('!')),
  map((arr) => {
    const [[greeting, subject], punctuation] = arr;
    return greeting + ' - ' + subject + punctuation;
  })
);

Stackblitz

If you have all the observables at hand you might also want to consider bineLatest which will bine the latest emitted values of each observable into an array. The number of elements in that array is equal to the number of observables you put in bineLatest:

const a$ = from(['a']);
const b$ = from(['b']);
const c$ = from(['c']);

const x$ =
  bineLatest([a$, b$, c$])
    .pipe(map(([a, b, c]) => `${a}.${b}.${c}`));
    
x$.subscribe(str => console.log(str));
<script src="https://unpkg./[email protected]/dist/bundles/rxjs.umd.min.js"></script>
<script>
const {from, bineLatest} = rxjs;
const {map} = rxjs.operators;
</script>

发布评论

评论列表(0)

  1. 暂无评论