To utilize the functionality of RxJS and ensure sequential execution, simply obtain a reference to the button, subscribe to the click event stream, and employ the flatMap
method to delegate the click event to an asynchronous function. With RxJS, you can maintain order without worrying about managing state.
Here is an example:
ionViewDidLoad() {
// Obtain a reference to the button (method of obtaining it doesn't matter)
const button = document.getElementById('queueEventButton')
// Create a stream of click events
Observable.fromEvent(button, 'click')
.flatMap(this.doTask) // Delegate each click event to the async process
.scan( (count: number) => count + 1, 0) // Counts mouse clicks for demonstration purposes
.subscribe(count => console.log(`Response received for click #${count}!`))
}
// Example async task simulating two seconds of processing
doTask(event: Event): Observable<Event> {
return Observable.fromPromise(new Promise(resolve => {
setTimeout(() => resolve(event), 2000)
}))
}