Last active
September 6, 2020 10:00
-
-
Save kuncevic/a8a88a4ddf52226aaf58595c1ed2b39f to your computer and use it in GitHub Desktop.
Reactive Services with BehaviourSubject
This file contains hidden or 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
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)); | |
} | |
} |
This file contains hidden or 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
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)); | |
} | |
} |
This file contains hidden or 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
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