Dimanoid
Dimanoid

Reputation: 7279

forkJoin or zip (or maybe some other function) list of observables with some kind of a progress

Is there a way to gather a list of observables together to get cumulative result like forkJoin or zip does, but get some kind of a progress while they finishes? For example join a list of similar http requests but visualize the progress while they goes.

Upvotes: 1

Views: 1054

Answers (2)

Oleksandr Poshtaruk
Oleksandr Poshtaruk

Reputation: 2146

One more possibility:

function get_result_and_perceptage(obs)
  const counter$ = new Subject();
  obs_modified_list = obs.map(item => item.pipe(finalize(
    () => counter$.next(1)
   ))

   const result$ = forkJoin(obs_modified_list).pipe(finalize(
     () => counter$.complete()
   ));

    const percent$ = counter$.asObservable().pipe(map((val)=>count *100/obs.length));
    return {result$, percent$};

Usage:

obs=[ob1,ob2,ob3]; // netwofk calls oservables

 const {result$, percent$} = get_result_and_perceptage(obs)
 result$.subscribe((resData)=>handleData(resData))
 percent$.subscribe(
    (percentValue) =>showItSomethere(percentValue),
    null,
    doSomethingWhenIsDone()
  )

Upvotes: 0

Fan Cheung
Fan Cheung

Reputation: 11345

Here is how you work out the percentage as each one of the observable completes. merge will let obs run async, scan will take a count and send to map to workout the percentage

obs=[ob1,ob2,ob3]
merge(...obs).pipe(
  scan((acc,curr)=>acc+1,0),
  map(count=>count/obs.length*100)
)

Upvotes: 1

Related Questions