Using RxJS Observable instead of setInterval() Method

This example shows how to use an RxJS Observable instead of the traditional JavaScript setInterval() method. This has several benefits, especially if you are unsing RxJS pervasively in your application code.

In this case, we want to obtain the device motion data in the defined interval from the Ionic Native module / Cordova Plugin.

There are two options:

  1. Configure a regular Observable to emit each interval
  2. Directly use IntervalObservable

Option 1: Observable

javascript

import { Observable } from 'rxjs/Observable';

// ...

// Define interval[ms]
const intervalMs = 100;

// Create a subscripton to the observable, so the observable is cancelable.
// The created observable is directly subscribed and the subscription saved.

let accelerationSensorSubscription = Observable.interval(intervalMs)
    .subscribe(() => {

        // Here goes all code that is started each interval
        this.deviceMotion
            .getCurrentAcceleration()
            .then(acceleration => {

                // Perform your action on the response
                console.log(acceleration);
            });
    });

Option 2: IntervalObservable

javascript

import { IntervalObservable } from 'rxjs/observable/IntervalObservable';

// ...

// Define interval[ms]
const intervalMs = 100;

// Create a subscripton to the observable, so the observable is cancelable.
// The created observable is directly subscribed and the subscription saved.

let accelerationSensorSubscription = IntervalObservable.create(intervalMs)
    .subscribe(() => {

        // Here goes all code that is started each interval
        this.deviceMotion
            .getCurrentAcceleration()
            .then(acceleration => {

                // Perform your action on the response
                console.log(acceleration);
            });
    });

Read more:

One thought on “Using RxJS Observable instead of setInterval() Method

  1. Great work! That is the type of info that are meant to be shared
    across the internet. Disgrace on Google for not positioning this post higher!

Leave a Reply

Your email address will not be published. Required fields are marked *