typescript - Cómo combinar 2 combineLatest para evitar la limitación de 6 argumentos
La cantidad máxima de argumentos que combineLatest puede tomar como entrada es 6.
Más específicamente, toma como entrada un arreglo que puede tener hasta 6 elementos. De esta manera, los tipos se infieren automáticamente.
Así que si en el código de abajo agrego this.someMethodReturningObservable7(), lo rompo:
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
);
}
Mientras lo limite a 6 argumentos, funciona bien. Con más de 6 no funciona.
¿Cómo puedo desglosar esto en varios combineLatest teniendo un máximo de 6 argumentos cada uno?
Respuesta #1
Puedes combinar dos combineLatests en uno así:
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));
Respuesta #2
Bueno, básicamente necesitas dividir el arreglo en fragmentos de 6 elementos, aplicar combineLates por fragmento y luego aplanar el arreglo resultante. Ejemplo:
/**
* 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()))
}
Ahora puedes llamar a este método en lugar de combineLatest, y acepta hasta 36 observables :)
