Skip to content

Share infinite stream produced by 'expand' #6780

Answered by emlautarom1
emlautarom1 asked this question in Q&A
Discussion options

You must be logged in to vote

The solution I ended up with involved creating an stateful Observable using closures. We kind of make our own version of share which it's bolted in to the Observable.

The only change is to mkInfiniteStream from the original code:

function mkInfiniteStream() {
  let lastPage = 0;
  let itemsRead = [];
  return defer(() =>
    from(itemsRead).pipe(
      concatWith(
        fetchPage(lastPage).pipe(
          expand((res) => fetchPage(res.page + 1)),
          tap((res) => {
            lastPage++;
            itemsRead = [...itemsRead, ...res.items];
          }),
          mergeMap((res) => from(res.items))
        )
      )
    )
  );
}

// Usage is still the same:
const infinite$ = mkIn…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by emlautarom1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants