Skip to content

Instantly share code, notes, and snippets.

@kuncevic
Last active September 6, 2020 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuncevic/a8a88a4ddf52226aaf58595c1ed2b39f to your computer and use it in GitHub Desktop.
Save kuncevic/a8a88a4ddf52226aaf58595c1ed2b39f to your computer and use it in GitHub Desktop.
Reactive Services with BehaviourSubject
export class CounterService {
private data$ = new BehaviorSubject<Counter>(initialState);
state$ = this.data$.asObservable();
constructor() {}
public setValue1(value1): void {
const currentData = this.data$.getValue();
this.data$.next({ ...currentData, value1: currentData.value1 + value1 });
}
public setValue2(value2: number): void {
const currentData = this.data$.getValue();
this.data$.next({ ...currentData, value2: currentData.value2 + value2 });
}
public setValue3(value3: number): void {
const currentData = this.data$.getValue();
this.data$.next({ ...currentData, value3: currentData.value3 + value3 });
}
public sum(): Observable<number> {
return this.data$.pipe(map((x) => x.value1 + x.value2 + x.value3));
}
}
export class CounterService extends RxService<Counter> {
constructor() {
super(initialState);
}
public setValue1(value1): void {
this.setState((state) => ({ ...state, value1: state.value1 + value1 }));
}
public setValue2(value2: number): void {
this.setState((state) => ({ ...state, value2: state.value2 + value2 }));
}
public setValue3(value3: number): void {
this.setState((state) => ({ ...state, value3: state.value3 + value3 }));
}
public sum(): Observable<number> {
return this.state$.pipe(map((x) => x.value1 + x.value2 + x.value3));
}
}
export class ParentComponent implements OnInit {
value$: Observable<number>;
constructor(private counterStore: CounterService) {}
ngOnInit(): void {
this.value$ = this.counterStore.state$.pipe(map((x) => x.value1));
}
updateValue(value: number): void {
this.counterStore.setValue1(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment