Blasco
Blasco

Reputation: 1745

Switching array of Observables into Observable of their results

The following code is working. It's purpose is to convert the results of a search, which returns the matching items, into the details of each matching item.

There is probably a better way to write this:

    fromEvent(this.searchInput.nativeElement, 'input').pipe(
      debounceTime(500),
    ).subscribe(async _ => {
      const results = await this.database.search(this.searchText);
      const arrayOfobservables = combineLatest(results.map(result => this.database.getDetails(result.objectID)));
      this.searchResults$.next(arrayOfobservables)
    });

    this.details$ = this.searchResults$.pipe(
      switchMap(val => val)
    )

The part I'm struggling is converting the array of observables, into an observable array that I can present in the UI.

Especially switchMap(val => val) looks very weird to me. Any ideas on how to actually make this code cleaner?

Upvotes: 0

Views: 61

Answers (1)

AliF50
AliF50

Reputation: 18889

You should be able to switchMap to a promise: https://stackoverflow.com/questions/44784660/how-does-switchmap-resolve-a-promise#:~:text=As%20you%20can%20see%2C%20getHero,()%20receives%20a%20Promise%20back.

Try:

this.details$ = fromEvent(this.searchInput.nativeElement, 'input').pipe(
      debounceTime(500),
      switchMap(_ => this.database.search(this.searchText)),
      switchMap(results => combineLatest(results.map(result => this.database.getDetails(result.objectID)))),
      tap(_ => { console.log(_) }), // see what you get here, it should hopefully be an array
    );

Upvotes: 1

Related Questions