Created
June 10, 2019 12:37
-
-
Save mccabiles/007eb843d78bcfbf5cd18ac90fd36986 to your computer and use it in GitHub Desktop.
Rxjs Behavior Subject for creating observable data.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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