简体   繁体   English

如何观察RxJS中的属性变化?

[英]How to observe property change in RxJS?

I don't have much experience with RxJS, but I was wondering if there is a way to subscribe to an object property change? 我没有RxJS的丰富经验,但我想知道是否有一种方法可以订阅对象属性更改? I am using RxJS 5. I use a BehaviorSubject to push new values to subscribers. 我正在使用RxJS5。我使用BehaviorSubject向订户推送新值。 The subject contains an object which defines some application settings. 该主题包含一个定义一些应用程序设置的对象。

So, what I want to do is, I want an application component to subscribe and get a new value when a specific property changes. 因此,我想做的是,我希望应用程序组件可以在特定属性更改时订阅并获取新值。 Alternatively, I would like the observable to produce a copy of the object for each subscriber - so they don't have a reference to the original object. 另外,我希望可观察对象为每个订阅者生成对象的副本-因此他们没有对原始对象的引用。

My question is similar to this one . 我的问题与类似。

The service that provides application settings: 提供应用程序设置的服务:

app.factory('settingsProvider', ['$rootScope', function ($rootScope) {

    let subject = new Rx.BehaviorSubject();

    let updateSettings = function (obj) {

        subject.next(_.merge({}, subject.getValue(), obj));
    };

    return {

        updateSettings: updateSettings,
        getObservable: function () {

            return subject.asObservable();
        }
    };
}]);

In some directive, I would than like to subscribe to a change to some property. 在某些指令中,我要订阅对某些属性的更改。 I currently have this: 我目前有这个:

let settings = {};
let settingsSubscription = settingsProvider.getObservable().subscribe(x => settings = x);

I believe you want the operator distinct . 相信您希望操作员distinct https://rxjs-dev.firebaseapp.com/api/operators/distinct https://rxjs-dev.firebaseapp.com/api/operators/distinct

It's an old question, so I'll give v6 syntax and assume you've updated in the meantime. 这是一个古老的问题,因此我将提供v6语法并假设您在此同时进行了更新。 The concept hasn't changed, so you could apply this approach in v5. 概念没有改变,因此您可以在v5中应用此方法。

The big error you're making is forcing settings to be reassigned above as a closure. 您正在犯的一个大错误是迫使settings在上面作为闭包重新分配。 Observables work best as streams, where you pipe one observable into the next and have no side-effects . 可观察变量作为流最有效,您将一个可观察变量通过管道传输到下一个变量,并且没有副作用 If we assume you start observing something that's building it like { foo: 1, bar: 2, baz: 3} , we can first map out the prop we want, then distinct on it to ensure we only emit on a change. 如果我们假设您开始观察构建它的东西,例如{ foo: 1, bar: 2, baz: 3} ,那么我们可以先map所需的道具,然后在其上进行distinct以确保仅在更改时发出。

 const fooUpdate$ = mySub$ .pipe( .map(({ foo }) => foo) .distinct() ); fooUpdate$.subscribe(val => console.log(val)); // Example of testing it mySub$.next({ foo: 1, bar: 2 }); mySub$.next({ foo: 1, bar: 3 }); mySub$.next({ foo: 2, bar: 4 }); mySub$.next({ foo: 2, bar: 5 }); mySub$.next({ foo: 2, bar: 5 }); mySub$.next({ foo: 3, bar: 2 }); // 1, 2, 3 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM