3.0.0 • Published 4 years ago

lite-observable v3.0.0

Weekly downloads
4
License
MIT
Repository
github
Last release
4 years ago

LiteObservable

Cold Observables for JS in just 617 bytes.

Usage

Installing

As a node module

npm i lite-observable
yarn add lite-observable

Creating an Observable

const observable = Observable.create(emitter => {
  emitter.next('Hello');
  emitter.next('World');
  emitter.complete();
});

Emitters have the following properties:

FieldTypeDescription
nextfunctionEmits a value.
errorfunctionEmits an error signal.
completefunctionEmits a completion signal.
subscriptionobjectThe subscription context.

Subscribing

observable.subscribe(
  x => console.log(`Next: ${x}`)
  e => console.log(`Error: ${e}`),
  () => console.log('Completed'),
);

Subscriptions have the following properties:

FieldTypeDescription
activefunctionReturns the current state of the subscription. Returns false if the subscription is disposed or finished.
disposefunctionDisposes the subscription.

Creating your own operators

With the pipe method, it is easy to create and use your own custom operators.

When constructing operators, it is recommended to use the constructor instead of create method to prevent subscription overhead, and to directly access the unabstracted Observer object. Use sub instead of subscribe to access the operator of the source Observable.

Example below is a map and filter operators:

const map = mapper => source => new Observable((o) => {
  const {
    subscribe, complete, error, next,
  } = o;
  source.sub({
    subscribe,
    next: x => next(mapper(x)),
    error,
    complete,
  });
});

const filter = predicate => source => new Observable((o) => {
  const {
    subscribe, complete, error, next,
  } = o;
  source.sub({
    subscribe,
    next: x => predicate(x) && next(x),
    error,
    complete,
  });
});

Example usage:

const observable = Observable.create((e) => {
  for (let i = 0; i < 10; i += 1) {
    e.next(i);
  }
  e.complete();
});

observable.pipe(
  filter(x => x % 2 === 0),
  map(x => x * 2),
  map(x => `Next: ${x}`),
).subscribe(
  console.log,
);

which outputs:

Next: 0
Next: 4
Next: 8
Next: 12
Next: 16
3.0.0

4 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago