Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including rxjs-observe with all npm packages installed. Try it out:

require("rxjs/package.json"); // rxjs is a peer dependency. var rxjsObserve = require("rxjs-observe")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

rxjs-observe v2.1.5

A library for observing an object's property assignments and method calls

rxjs-observe

GitHub License NPM version Build status dependency status devDependency Status peerDependency Status

What is it?

It's an observe function that can be used to create observable sources for an arbitrary object's property assignements and method calls.

Why might you need it?

If you need to convert an imperative API to an observable API, you might find this useful.

Install

Install the package using NPM:

npm install rxjs-observe --save

TypeScript 3.0 or later is required, as the type declaration for observe uses generic rest parameters.

Usage

Pass an object instance to observe and receive an observables object - that contains observable sources for the object's properties and methods - and a proxy:

import { observe } from "rxjs-observe";

const instance = { name: "Alice" };
const { observables, proxy } = observe(instance);
observables.name.subscribe(name => console.log(name));
proxy.name = "Bob";

observe can be passed optional callbacks that will be implemented in the proxy - the observed instance does not need to implement them - and forwarded to an observable with the same name:

import { callback, observe } from "rxjs-observe";

const instance = { name: "Alice" };
const { observables, proxy } = observe(instance, {
  init: callback()
});
observables.init.subscribe(() => console.log("init"));
proxy.init();

observe can be called inside a constructor and the proxy can be returned, as in this Angular component:

import { Component, Input, OnInit, OnDestroy } from "@angular/core";
import { switchMapTo, takeUntil } from "rxjs/operators";
import { callback, observe } from "rxjs-observe";

@Component({
  selector: "some-component",
  template: "<span>Some useless component that writes to the console</span>"
})
class SomeComponent {
  @Input() public name: string;
  constructor() {
    const { observables, proxy } = observe(this as SomeComponent, {
      ngOnInit: callback(),
      ngOnDestroy: callback()
    });
    observables.ngOnInit.pipe(
      switchMapTo(observables.name),
      takeUntil(observables.ngOnDestroy)
    ).subscribe(value => console.log(value));
    return proxy;
  }
}

However, such a component implementation is ... unconventional, so proceed with caution, but ... YOLO.

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free