Fila de Observables

Asked

Viewed 74 times

-1

My application has a service that runs an observable every time I click a button. The problem is that if I click several times on the button it runs the Observable several times at the same time. I needed this service to queue up and run 1 at a time. What better way to do this?

EDIT: Source

// component
onClick(record){
  this.myService.updateRecord(params).subscribe();
}

// service
updateRecord(record){
  return new Observable((observer) => {
    Observable.forkJoin(
      Observable.fromPromise(this.storage.get('things')),
      Observable.fromPromise(this.storage.get('other_things'))
    ).subscribe(
      (results) => {
        let things = results[0] || []
        let other_things = results[1] || []

        // do stuffs 

        observer.next([record])
        observer.complete()
      })
  })
}
  • could show the source code of how this is being done?

  • added @mercador

1 answer

0


Solved based on that answer: https://stackoverflow.com/questions/44769327/chain-observable-queue

// component
onClick(record){
  this.myService._updateRecord(params).subscribe();
}

// service
private trigger= undefined;

updateRecord(record){
  return new Observable((observer) => {
    Observable.forkJoin(
      Observable.fromPromise(this.storage.get('things')),
      Observable.fromPromise(this.storage.get('other_things'))
    ).subscribe(
      (results) => {
        let things = results[0] || []
        let other_things = results[1] || []

        // do stuffs 

        observer.next([record])
        observer.complete()
      })
  })
}

obsQueue(record) {
  if (!this.trigger || this.trigger.isStopped) {
    this.trigger = new Subject();
    return this.createObservable(this.trigger, record);
  } else {
    var lastTrigger = this.trigger;
    var newTrigger = this.trigger = new Subject();
    return lastTrigger.last().mergeMap(() => {
      return this.createObservable(newTrigger, record);
    });
  }
}


createObservable(trigger, record) {
  return this.updateRecord(record).finally(() => {
    trigger.next();
    trigger.complete();
  });
}


_updateRecord(record){
  return this.obsQueue(record);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.