简体   繁体   中英

Observable Pagination for infinite scroll to stay up to date

I am trying to get my observable to update automatically during pagination.

Only Page Trigger

When load() is called, the page observable gets triggered, but the subscription observable does not get triggered when it is updated...

pageSub = new BehaviorSubject<number>(1);
page = 1;

// in constructor...

this.posts = this.pageSub
  .pipe(
    mergeMap((page: number) => this.urql
      .subscription(this.GET_POSTS,
        {
          first: this.ITEMS.toString(),
          offset: (this.ITEMS * (page - 1)).toString()
        }
      )
    ),
    scan((acc, value) => [...acc, ...value]),
  );

// called from button

load() {
  this.page += 1;
  this.pageSub.next(this.page);
}

Only Subscription Trigger

Here a subscription change does get triggered, but when load() is called, a page change does not get triggered...

this.posts = combineLatest([this.pageSub, this.urql
  .subscription(this.GET_POSTS,
    {
      first: this.ITEMS.toString(),
      offset: (this.ITEMS * (this.page - 1)).toString()
    }
  )]).pipe(
    map((arr: any[]) => arr[1])
  );

Surely, there is a way so that the Observable gets updated with a page change and with a subscription change?

I should add that resetting the variable declaration this.posts does not work, as it refreshed the page and is not intended behavior.

Any ideas?

Thanks,

J

Got it:

mainStream: BehaviorSubject<Observable<any>>;

posts!: Observable<any>;

constructor(private urql: UrqlModule) {

  this.mainStream = new BehaviorSubject<Observable<any>>(this.getPosts());

  this.posts = this.mainStream.pipe(mergeAll());

}

async load() {
  this.page += 1;
  this.mainStream.next(this.combine(this.mainStream.value, this.getPosts()));
}

getPosts() {
  return this.urql.subscription(this.GET_POSTS,
    {
      first: this.ITEMS.toString(),
      offset: (this.ITEMS * (this.page - 1)).toString()
    }
  )
}

combine(o: Observable<any>, o2: Observable<any>) {
  return combineLatest([o, o2]).pipe(
    map((arr: any) => arr.reduce((acc: any, cur: any) => acc.concat(cur)))
  );
}

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