Sampath
Sampath

Reputation: 65870

Access a value from setTimeout Observable method

Can you tell me how to access a value from the async setTimeout() observable method? I have written just normal async method as below.But as we all know it doesn't do what I need.How can I use observable here? Any guidance would be really appreciated.

page.ts

loader = this.loadingControllerService.dismissLoaderWhenNoInternet(loader);

provider.ts

 dismissLoaderWhenNoInternet(loader: Loading): Loading {
    setTimeout(() => {
      if (loader) {
        loader = null;
        return loader;//not working here
      }
    }, 5000);
    return loader;
  }

Upvotes: 8

Views: 19242

Answers (1)

Duannx
Duannx

Reputation: 8726

To deal with async in es6 you have 2 choices:
Promise: use for function just return once time:

asyncPromise() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("Hello");
      }, 2000)
    })
}

this.asyncPromise().then(data=>{console.log(data)}); //Print Hello after 2s

Observable: use for function return more than once time:

import { Observable } from 'rxjs/Observable';
asyncObservable() {
    return new Observable(observer => {
      setInterval(() => {
        observer.next("Hi");
      }, 1000)
    })
}

this.asyncObservable().subscribe(data=>{console.log(data);}) //Print Hi every 1s

See more about differences between Promise and Observable

Upvotes: 15

Related Questions