I have a sidebar, and when you make changes to it I need to subscribe to those changes and react to them so we are using a Subject.
The thing is we don't know the best architecture for a Subject, should it be a single string emitted or an object?
If we emit an object of all the changes as key:value pairs, how do we subscribe to just one of those changes elsewhere instead of reacting to the entire object?
I want to void polluting my code with a Subject emitter for every change or is that the "best practice"
Example of current implementation
Emitter
/**
* A function that emits an RXJS event to any observers subscribed to this subjet
* when the user changes the calendar in the sidebar.
* @return {Observable} An Observable that, whenever subscribed, will execute the
* specified function.
* @static false
*/
public emitCalendar = (calendar: any): void => {
this.selectedCalendar = calendar;
this.onChangeLeftPane$.next({ calendar: calendar });
};
And then what is the best way to subscribe just to
onChangeLeftPane$.calendar
Setup a separate Observable to listen to change with filter
operator
this.onChangeCalendar=this.onChangeLeftPane$.asObservable()
.pipe(filter(obj=>Objects.keys(obj).includes('calendar'))
this.onChangeLeftPane$.next({ calendar: calendar });
You can use pluck
to only get the calendar
from your object and then if necessary add filter
(so that you don't emit undefined
if calendar
is missing) and/or distinctUntilChanged
(so that you don't emit the same value twice if it didn't change).
import { pluck, filter, distinctUntilChanged } from 'rxjs/operators';
onChangeLeftPane$.pipe(
pluck('calendar'), // extract the property 'calendar' from the object
filter(Boolean), // don't emit if the property 'calendar' was missing from the object
distinctUntilChanged(), // only emit if this calendar is distinct from the previous one
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.