Skip to content

Instantly share code, notes, and snippets.

@NyaGarcia
Created March 20, 2020 15:13
Show Gist options
  • Save NyaGarcia/c049b7c8c2fb5ce9477b061600ffe6c1 to your computer and use it in GitHub Desktop.
Save NyaGarcia/c049b7c8c2fb5ce9477b061600ffe6c1 to your computer and use it in GitHub Desktop.
Preserving class encapsulation by providing methods to interact with Subjects
class DataService {
private pokemonLevel = new BehaviorSubject<number>(1);
private stop$: Subject<void> = new Subject();
pokemonLevel$ = this.pokemonLevel.asObservable();
increaseLevel(level: number) {
if (!this.isValidLevel(level)) {
throw new Error("Level is not valid");
}
this.pokemonLevel.next(level);
}
stop() {
this.stop$.next();
}
private isValidLevel(level: number): boolean {
return level % 2 === 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment