Displaying paginated data using RXJS expand operator

mustafa kachwala
2 min readOct 18, 2020

--

While working on one project, the requirement was to load a paginated dataset of users. The API was returning paginated data with page cursor. This could have been handled in a number of ways. The data had to be shown in a table.

I implemented this requirement by using the expand operator provided by RXJS.

The beauty of this operator is in its implementation. The operator allows us to chain all the paginated response and provides us with a stream of all the paginated data. There is no need to handle the page cursor. The operator handles the same and once all the pages are retrieved, it automatically ends the stream.

Considering the API which return the data has the below interface

export interface IUsersResponse {
users: any[];
pagecursor?: string
}

export class UserService {
constructor(private httpClient: HttpClient) {} fetchUsers(): IUserResponse {
return this.httpClient.get('<user-api>');
}
}

With the help of the expand operator, we can fetch the data as shown below:


let userData$ = UserService.fetchUsers().expand((res: IUsersResponse) => {
if(!res?.pagecursor){return EMPTY}
else {
return UserService.fetchUsers()
}
})

Hence, from the code, you can see that the expand operator will make sequential calls in a recursive fashion, to fetch all the paginated data and return EMPTY when complete.

The benefit of using this allows for a better user experience, as a obstructive loading spinner is only required for the first API call. Once the first page is loaded, the UI can be rendered and all subsequent calls keep appending the data to the end of the dataset. The subsequent loading of paginated APIs can still be shown, but in an un-obstructive manner like a progress bar, until all the data is loaded.

If you liked this article, please do clap :)

Read my other articles on RXJS operators:

--

--

mustafa kachwala
mustafa kachwala

No responses yet