TypeScript - איך לשלב שני combineLatest כדי לעקוף את המגבלה של 6 פרמטרים


הכמות המקסימלית של ארגומנטים ש-combineLatest יכול לקבל כקלט היא 6.

במילים אחרות, הוא מקבל כקלט מערך אחד שיכול להכיל עד 6 אלמנטים. באופן זה סוגים נלקחים אוטומטית.

אז אם בקוד למטה אני מוסיף this.someMethodReturningObservable7() אני שוברת את זה:

someMethod(...) {
  return combineLatest([
    this.someMethodReturningObservable1(),
    this.someMethodReturningObservable2(),
    this.someMethodReturningObservable3(),
    this.someMethodReturningObservable4(),
    this.someMethodReturningObservable5(),
    this.someMethodReturningObservable6(),
    this.someMethodReturningObservable7(), // this causes problems
  ]).pipe(
    map(([arg1, arg2, arg3, arg4, arg5, arg6, arg7]) => ({
      arg1,
      arg2,
      arg3,
      arg4,
      arg5,
      arg6,
      arg7,
    })),
    // do more stuff
  );
}

כל עוד אני שומר על 6 ארגומנטים, זה עובד בסדר. עם יותר מ-6 זה לא עובד.

איך אני יכול לפרק את זה למספר combineLatest כאשר כל אחד מכיל מקסימום 6 פרמטרים?

תשובה #1

אתה יכול לשלב שני combineLatest לאחד ככה:

import { of, combineLatest, interval } from "rxjs";
import { map, take } from "rxjs/operators";

const num0$ = of(0 as const);
const num1$ = of(1 as const);
const num2$ = of(2 as const);
const num3$ = of(3 as const);
const num4$ = of(4 as const);
const num5$ = of(5 as const);
const num6$ = of(6 as const);
const num7$ = of(7 as const);
const num8$ = of(8 as const);
const num9$ = interval(1000).pipe(take(3), map(() => 9 as const));

const numsPartOne$ = combineLatest(num0$, num1$, num2$, num3$, num4$);
const numsPartTwo$ = combineLatest(num5$, num6$, num7$, num8$, num9$);

const numCombined$ = combineLatest([numsPartOne$, numsPartTwo$]).pipe(
  // use [[..] [..]] to spread both arrays
  map(([[num0, num1, num2, num3, num4], [num5, num6, num7, num8, num9]]) => {
    // num0 has type 0, etc.
    return {
      num0,
      num1,
      num2,
      num3,
      num4,
      num5,
      num6,
      num7,
      num8,
      num9
    };
  })
);
numCombined$.subscribe(mappedNums => console.log(mappedNums));

תשובה #2

ובכן, בעצם אתה צריך לחלק את המערך לחתיכות של 6 אלמנטים, להחיל combineLates על כל חתיכה ואז לשטח את מערך התוצאה. דוגמה:

  /**
   * Overcoming limitation on 6 observables in the combineLatest
   */
  private combineMoreLatest(args: Array<Observable<unknown>>): Observable<unknown> {
    const limit = 6;
    const length = parseInt((args.length / limit) + '') + 1;
    return combineLatest(
      Array.from({ length })
        .map((_, i)=> args.slice(i * limit, (i + 1) * limit))
        .map(arr => combineLatest(arr))
      )
      .pipe(map(combined => combined.flat()))
  }

עכשיו אתה יכול לקרוא לשיטה זו במקום ל-combineLatest, והיא מתקבלת עד 36 אובזרבבלס :)