Rx JS: последовательно объединить переменное число внутренних наблюдаемых - PullRequest
0 голосов
/ 17 апреля 2020

Мне нужно последовательно конкатенировать переменное число внутренних наблюдаемых и остановиться, как только первый разрешится с заданным результатом. См. Пример ниже или здесь, на Stackblitz , где я использую concatMap, но это работает только с фиксированным числом внутренних наблюдаемых.


const values = [1, 4, 6, 3, 9];

getRemoteValue(values[0]).pipe(
  concatMap(result => result ? of(result) : getRemoteValue(values[1])),
  concatMap(result => result ? of(result) : getRemoteValue(values[2])),
  concatMap(result => result ? of(result) : getRemoteValue(values[3])),
  concatMap(result => result ? of(result) : getRemoteValue(values[4]))
).subscribe(success => console.log(success ? 'found it' : 'failed'));



function getRemoteValue(input: number): Observable<boolean> {
  console.log(`checking ${input}`)
  // this would be an async remote call in real life
  const value = _.random(10); 
  return of(value === input);
}

1 Ответ

2 голосов
/ 17 апреля 2020
import * as _ from 'lodash';
import { Observable, of, from, EMPTY } from 'rxjs';
import { concatMap, single, find } from 'rxjs/operators';

const values = [1, 4, 6, 3, 9];

function getRemoteValue(input: number): Observable<boolean> {
  console.log(`checking ${input}`)
  // this would be an async remote call in real life
  const value = _.random(10);
  return of(value === input);
}

from(values).pipe(
  concatMap(getRemoteValue),
  find((v) => typeof v === 'boolean' && v === true)
)
.subscribe(success => {
    console.log('success:', success);
    console.log(success ? 'found it' : 'failed');
  }
);

стекаблиц

...