Aditya
Aditya

Reputation: 2536

How to write a function with an Observable?

I want to create a function that returns an Observable.The description of the function is as follows:

  1. The function should be delayedAlert(message:string, time:number) that returns an Observable.

  2. The function should contain setTimeout function inside delayedAlert which prints message after the set 'time' value.

Ex:

delayedAlert(message, time){
return new Observable//how to implement setTimeout function here?

Upvotes: 1

Views: 1435

Answers (1)

user663031
user663031

Reputation:

Use Observable.create to create the observable, and in the first callback, write the logic to populate the observable, which in your case is the setTimeout.

function delayedAlert(msg, time) {
  return Observable.create(
    observer => setTimeout(() => observer.onNext(msg), time));
}

Then to use it:

delayedAlert("Hi, Sally", 1000).subscribe(msg => alert(msg));

However, if you are using observables, you don't need to use setTimeout; use delay instead, applied to of, which creates an observable from individual value(s):

function delayedAlert(msg, time) {
  return Observable.of(msg).delay(time);
}

Since it's so easy to write it this way, you probably don't need the delayedAlert function at all:

const observable = Observable.of("Hi, Sally").delay(1000);

observable.subscribe(msg => alert(msg));

Upvotes: 4

Related Questions