8

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;
  }
Sampath
  • 63,341
  • 64
  • 307
  • 441

1 Answers1

15

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

Duannx
  • 7,501
  • 1
  • 26
  • 59
  • Sorry, This is not what I need.I just need to print `Hi` only after `1 sec` and that's it.I would like to have an `observable` solution too. – Sampath Jul 24 '17 at 04:36
  • If you want print `Hi` only after `1s`, why you dont use `Promise`. `Promise` and `Observale` is 2 different techniques to deal with `async` and each have its own purpose. You should base on your purpose to choose technique. But, in the end, it doesn't even matter. If you change `setInterval` to `setTimeout` you will print `Hi` only after `1s` – Duannx Jul 24 '17 at 04:51
  • 1
    it's better to name `observer`, not `observable` here `Observable(observable` – Max Koretskyi Jul 24 '17 at 06:31
  • 2
    If you want to print `Hi` after 1 sec and want an `rxjs` solution, you can use `timer()`: `Observable.timer(1000).mapTo('Hi').subscribe(x => console.log(x));` or `delay()`: `Observable.of('Hi').delay(1000).subscribe(x => console.log(x));`. – Sergey Karavaev Jul 25 '17 at 18:57