-
-
Save vladsadretdinov/9181c810d379e0920955160f2195283b to your computer and use it in GitHub Desktop.
An example of simple immutable RxJs store in Angular.
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 { Injectable } from '@angular/core'; | |
import { BehaviorSubject, Subject } from 'rxjs'; | |
import { PuppiesModule } from './puppies.module'; | |
import { Puppy } from './puppy.model'; | |
// How to debug RxJs | |
// https://blog.angular-university.io/debug-rxjs/ | |
// Как управлять состоянием в Angular по мере роста приложения | |
// https://habr.com/ru/company/custis/blog/516290/ | |
// Angular 2 и внедрение зависимостей | |
// https://habr.com/ru/post/281449/ | |
@Injectable({ providedIn: PuppiesModule }) | |
export class PuppiesStoreService { | |
// Make _puppiesSource private so it's not accessible from the outside, | |
// expose it as puppies$ observable (read-only) instead. | |
// Write to _puppiesSource only through specified store methods below. | |
private readonly _puppiesSource = new BehaviorSubject<Puppy[]>([]); | |
// Exposed observable (read-only). | |
readonly puppies$ = this._puppiesSource.asObservable(); | |
constructor() {} | |
// Get last value without subscribing to the puppies$ observable (synchronously). | |
getPuppies(): Puppy[] { | |
return this._puppiesSource.getValue(); | |
} | |
private _setPuppies(puppies: Puppy[]): void { | |
this._puppiesSource.next(puppies); | |
} | |
addPuppy(puppy: Puppy): void { | |
const puppies = [...this.getPuppies(), puppy]; | |
this._setPuppies(puppies); | |
} | |
removePuppy(puppy: Puppy): void { | |
const puppies = this.getPuppies().filter(p => p.id !== puppy.id); | |
this._setPuppies(puppies); | |
} | |
adoptPuppy(puppy: Puppy): void { | |
const puppies = this.getPuppies().map(p => | |
p.id === puppy.id ? new Puppy({ ...p, ...{ adopted: true } }) : p | |
); | |
this._setPuppies(puppies); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment