简体   繁体   English

将数组的可观察对象转换为可观察对象的数组

[英]Convert observable of array into array of observables

I am trying to convert from an observable of an array:我正在尝试从数组的可观察值进行转换:

of([1, 2, 3]);

Into an array of observables:进入一个可观察的数组:

[ of(1), of(2), of(3) ]

But I am out of ideas.但我没有想法。 I have tried the following:我尝试了以下方法:

of([1, 2, 3]).pipe(map((elements: number[]) => elements.map(element => of(element)))

But this gives me something like this, with an outer observable that I do not desire.但这给了我这样的东西,带有我不想要的外部可观察性。

of([ of(1), of(2), of(3) ])

As I want to join the result with other arrays, it is not convenient for me to just subscribe to the outer observable in order to get the array... I think I need an opposite operator of concatAll .因为我想将结果与其他 arrays 一起加入,所以我不方便只订阅外部 observable 来获取数组......我想我需要一个concatAll的相反运算符。 Any ideas?有任何想法吗?

If you know that the observable is always going to be totally synchronous (but keep in mind this is not really something you can check at runtime), you can do this:如果你知道observable 总是完全同步的(但请记住,这并不是你可以在运行时检查的东西),你可以这样做:

const extractValue = <T>(source$: Observable<T[]>): Observable<T>[] => {
  let result: Observable<T>[];
  source$
    .pipe(
      map((arr) => arr.map((value) => of(value))),
      take(1)
    )
    .subscribe((_result) => {
      result = _result;
    });
  return result;
};

Otherwise, you must use an async function:否则,您必须使用异步 function:

const extractValue = <T>(
  source$: Observable<T[]>
): Promise<Observable<T>[]> => {
  return source$
    .pipe(
      map((arr) => arr.map((value) => of(value))),
      take(1)
    )
    .toPromise();
};

RxJS#from RxJS#来自

from([1,2,3,4,5]).subscribe(console.log) // 1 2 3 4 5

or as a pipable operator或作为可管道操作员

of([1,2,3,4,5]).pipe(
  concatMap(v => from(v))
).subscribe(console.log) // 1 2 3 4 5

Combine that with your transformation将其与您的转型相结合

of([1,2,3,4,5]).pipe(
  map((elements: number[]) => 
    elements.map(element => of(element))
  ),
  concatMap(x => from(x))
)

combined结合

of([1,2,3,4,5]).pipe(
  concatMap((elements: number[]) => 
    from(elements.map(element => of(element)))
  )
)

Maybe you can try to create an Observable from an array and than turn each member in to an Observable using of() function:也许您可以尝试从数组创建一个 Observable,然后使用 of() function 将每个成员转换为 Observable:

const arr = [1, 2, 3];

from(arr).pipe(
  mergeMap((a) => of(a))
);

After that you can handle each observable as you please.之后,您可以随意处理每个 observable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM