0.7.1 • Published 2 years ago

@taqtile/ts-thenable-rx v0.7.1

Weekly downloads
76
License
MIT
Repository
github
Last release
2 years ago

Typescript Thenable RX extensions

Thenable RXjs extensions

Contents

Observable Promise

ObservablePromise is an extension of Promise adding a asObservable method which creates an Observable from a promise.

General use

function returningPromise(): Promise<any> {
  /* ... */
}

const observablePromise = new ObservablePromise(returningPromise);

// can be used as Promise
observablePromise
  .then(/* ... */);

// or as observable
observablePromise
  .asObservable()
  .subscribe(
    /* ... */
  );

!!! Warning !!!

  • ObservablePromise defers the creation of a promise. The real promise will be created when a then, catch or subscribe is invoked.

Promise generator's context

It's also possible to pass a context to the promise generator function:

function returningPromise(): Promise<number> {
  return Pomise.resolve(this.value);
}

const context = { value: 1 };

const observablePromise = new ObservablePromise(returningPromise, context);

observablePromise
  .asObservable()
  .subscribe(console.log); // 1

This is specially usefull when you want to invoke a class method:

class MyClass {
  constructor(private aMember: number) { }

  public deferMemberValue(): Promise<number> {
    return Promise.resolve(this.aMember);
  }
}

const anInstance = new MyClass(1);

const observablePromise = new ObservablePromise(MyClass.prototype.deferMemberValue, anInstance);

observablePromise
  .asObservable()
  .subscribe(console.log); // 1

As Observable Promise decorator

Intead of manually creating an ObservablePromise object you can automatically convert a method returning promise into an observable-promise by decorating a class method:

class SomeClass {
  @AsObservablePromise()
  returningObservablePromise(): ObservablePromise<string> {
    return this.returningPromise();
  }

  returningPromise(): Promise<string> {
    return Promise.resolve('some value');
  }
}
0.7.1

2 years ago

0.6.0

3 years ago

0.5.0

5 years ago

0.4.0

5 years ago

0.3.3-alpha.1

5 years ago

0.3.3-alpha.0

5 years ago

0.2.2

6 years ago

0.2.1

6 years ago

0.2.0

6 years ago