[英]How can I emit an object of changes as a subject and subscribe to only one key changing?
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? 如果我们将所有更改的对象作为key:value对发出,我们如何仅在其他位置订阅那些更改之一,而不是对整个对象做出反应?
I want to void polluting my code with a Subject emitter for every change or is that the "best practice" 我想对每次更改都使用Subject发射器来污染我的代码,或者这是“最佳实践”
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 设置一个单独的Observable以使用
filter
运算符侦听更改
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). 您可以使用
pluck
仅从对象中获取calendar
,然后在必要时添加filter
(这样,如果缺少calendar
则不会发出undefined
)和/或distinctUntilChanged
(这样,如果它不发出相同的值,则不会两次)没有变化)。
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
)
https://stackblitz.com/edit/typescript-eoyqi9 https://stackblitz.com/edit/typescript-eoyqi9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.