Ricerca nel sito web

typescript - paginazione rxjs con sottoscrizione a ogni pagina


Stiamo interrogando graphql tramite websocket per avere una sottoscrizione a una lista di entità. Usiamo la paginazione poiché la lista dovrebbe essere scorrevole indefinitamente. Vogliamo anche vedere le modifiche apportate al database in tempo reale nella lista sul front-end.

Questa lista può essere filtrata, ordinata e impaginata.

Abbiamo la classe SelectParams che ci aiuta a fare ciò:

export class SelectParams {
    page = 0;
    query = '';
    sort: Sort = { sortBy: 'creationDate', sortOrder: 'DESC' };
    take = 30;
}

Poi, quando vogliamo iscriverci a una lista, basta dare un selectParams$=Observable<SelectParams> per ottenere la lista che è "reattiva" e reagisce ai cambiamenti in selectParams$. Questo viene usato così:

    this.items$ = this.featureSrv.selectMany(this.selectParams$)

Sotto il cofano, il selectMany funziona così:

// when we call selectMany we just push the params to the pipeline
selectMany(params$: Observable<SelectParams> = of(new SelectParams())): Observable<T[]> {
    this.selectManyParams$.next(params$);
    return this.selectMany$;
}

// subject where we push params to sort, paginate and filter
selectManyParams$ = new ReplaySubject<Observable<SelectParams>>(1);
// when the params change then so does this observable, which is returned by the selectMany function
selectMany$ = this.selectManyParams$.asObservable().pipe(
    // retrieve params from their observable form
    flatMap(params$ => params$),
    // when the params haven't changed we shouldn't do anything
    distinctUntilChanged(),
    // then we query graphql to get a suscription to some part of the data
    switchMap(({ page, sort, query, take }: SelectParams) => {
    // the selectMany here is a subscription to some data on the server
        return this.apolloWrapper.selectMany(this.gql, page, sort, query, take ).pipe(
    // we add page data so we can use it in the scan
            map(data => ({ data, page }) as any)
        );
    }),
    // we append the result if page was incremented
    // else we just return the result
    scan((acc: any, curr: any) => curr.page === 0 ? curr.data : acc.concat(curr.data), [])
);

Il metodo this.apolloWrapper.selectMany è un metodo che abbiamo creato che semplicemente fa una sottoscrizione tramite websocket a una parte dei dati. Supponiamo di avere page=0, allora this.apolloWrapper.selectMany restituirà una sottoscrizione alla prima parte dei dati, poi quando page=1, this.apolloWrapper.selectMany restituirà una sottoscrizione alla seconda parte dei dati.

Il problema sorge quando carichiamo la seconda pagina e apportiamo una modifica agli elementi della prima fetta, il scan viene quindi attivato e gli elementi vengono riaggiunti alla fine della lista.