如何使用RXJS实现分页解决方案



在RXJS中实现分页解决方案的最佳方法是什么?

如果要具有基于事件的可观察到的可观察到新数据(可以单击或JavaScript函数调用)。例如,如果我有一个可观察到的数据从Web API检索数据,并且我不希望它只是继续锤击HTTP请求,我只希望在订户触发的事件中发生这种情况。场景可以是无限的滚动(通过滚动触发的事件),经典分页(通过用户单击下一页触发的事件)等。

这是我根据评论提出的解决方案,并使用RXJS 6.3.3

export default class Test extends React.Component<any, any> {
  private subscription: Subscription;
  public componentDidMount() {
    const client = new MyClient();
    let source = client.get('/data');
    const buttonNotifier = defer(() => {
      console.log("waiting");
      return fromEventPattern(
        (handler) => { this.next = handler; }
      ).pipe(tap(() =>
        console.log("sending more data")
      ));
    });
    const pagedData: Observable<{Value:any, NextLink:string}> = source.pipe(
      expand(({ NextLink }) => NextLink ?
      buttonNotifier.pipe(take(1), concatMap(() => client.get(NextLink))) :
      empty()));
    this.subscription = pagedData.subscribe(
      result => {
          this.setState({
          Value: result.Value,
        });
      },
      error => {
        this.setState({
          Error: `ERROR: ${error}`
        });
      },
      () => {
        this.setState({
          Done: `DONE`
        });
      }
    );
  }
  public componentWillUnmount() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
  private next: Function;
  public render(): React.ReactElement<any> {
    return (<button onClick={()=> {this.next();}}>Next</button>);
  }
}

最新更新