【问题标题】:Task queue with observables [closed]带有可观察对象的任务队列[关闭]
【发布时间】:2018-12-12 07:52:50
【问题描述】:

我有这种情况:我的应用程序的用户可以点击一个按钮来执行一项任务,而该任务需要 2 秒才能完成。我想创建一个队列来按顺序连续执行每个任务。

我正在使用带有 TypeScript 的 Ionic 3。

最好的方法是什么?

【问题讨论】:

    标签: javascript typescript ionic-framework ionic3 observable


    【解决方案1】:

    我只是获取按钮的引用,订阅点击事件流,然后使用flatMap 将点击事件传递给执行任务的任何异步函数。 RxJS 将确保一切都按顺序执行,而 Rx 的美妙之处在于您不必管理任何状态。

    例子:

    ionViewDidLoad() {
      // grab a reference to your button.  Doesn't matter how you do it.
      const button = document.getElementById('queueEventButton')
    
      // Create the stream of clicks
      Observable.fromEvent(button, 'click')
        .flatMap(this.doTask) // pass each click event off to the async process
        .scan( (count: number) => count + 1, 0) // this just counts the mouse click, useful for example
        .subscribe(count => console.log(`Response received for button click #${count}!`))
    }
    
    // example task that simulates two second processing
    doTask(event: Event): Observable<Event> {
      return Observable.fromPromise(new Promise(resolve => {
        setTimeout(() => resolve(event), 2000)
      }))
    }
    

    【讨论】:

    • 昨晚正在考虑这个问题,并认为您可能想要控制队列的并发性...这里有一个使用 rxjs@6 jsfiddle.net/helvetici/npx1cyL2/55 的小提琴您想使用 flatMapWithMaxConcurrent如果我没记错的话,我相信 Rx 5 是 Ionic 3 附带的。您必须查找 rx 版本之间的 api 更改,但操作符是相同的。
    猜你喜欢
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2018-01-23
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多