Skip to content

Instantly share code, notes, and snippets.

@mccabiles
Created June 10, 2019 12:37
Show Gist options
  • Save mccabiles/007eb843d78bcfbf5cd18ac90fd36986 to your computer and use it in GitHub Desktop.
Save mccabiles/007eb843d78bcfbf5cd18ac90fd36986 to your computer and use it in GitHub Desktop.
Rxjs Behavior Subject for creating observable data.
import { BehaviorSubject } from 'rxjs';
export class SomeServiceClass {
constructor() {
this.dataObject = new BehaviorSubject('some initial value');
}
set setData(newData) {
// notify all subscribed listeners to update data:
this.dataObject.next(newData);
}
get getData() {
return this.dataObject.getValue();
}
updateData(someNewData) {
this.setData = someNewData;
}
}
// In some other class:
class ServiceConsumer {
constructor(service: SomeServiceClass) {
this.dataObject = '';
// Whenever the value of the dataObject of our SomeServiceClass is updated,
// the ServiceConsumer's dataObject will also update:
this.service.dataObject.subscribe(newDataObject => this.dataObject = newDataObject);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment