简体   繁体   中英

refactor a subscription into an observable

I am using a method query_character to return a promise that makes multiple http-requests. Then I emit that value to a subject this.search_result$ . This works as expected, but I want to get rid of those ugly embedded subscriptions and return an array of results from the subscription instead.

private query_character(query): void {
    this.api.fetch_character_query(query)
    .subscribe( query_responses => {
      query_responses.subscribe( characters => {
        this.search_result$.next( characters )
      });
    })
  }

The fetch_character_query that is beng called:

  public fetch_character_query( query ): any {
    return this.http.get<any>(`some-url`)
    .pipe( map( character_ids => {
      // NOTE:  fetch_character_info returns an Observable
      return character_ids.character.map( character_id => this.fetch_character_info(character_id) ); 
    }))
    .pipe( map( characters => forkJoin( characters ) ) )
  }

How can I return an array with results (resolved observables from this.fetch_character_info ) instead of an array of observables?

public fetch_character_query( query ): any {
    return this.http.get<any>(`some-url`)
    .pipe( 
       mergeMap(character_ids => character_ids), //will emit each character id
       mergeMap(id => this.fetch_character_info(character_id).pipe(
           map(res => change into shape you need here),
           catchError(err => handle it)
       ),
       toArray(),
       catchError(err => handle it)
     )

https://rxjs.dev/api/operators/toArray

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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