Issue
I want to observe changes of a property with RxJS.
interface Test {
required: boolean;
toObserve: boolean;
}
class TestClass {
@Input() subject: Subject<Test>;
registerHandlers() {
this.subject.filter(element => element.required).subscribe(next =>
// Observe a property of every element that was registered
Observable.of(next.toObserve).subscribe(val => {
if (val) {
// DO SOMETHING
} else {
// DO SOMETHING ELSE
}
})
);
}
}
I got a subject into which newly created objects are pushed. Several components subscribe on these and should react on different property changes.
In the above example if toObserve is set I want the component to do something. This works exactly once currently - Depending on the value the element has when it is registered with subject.next(element) the correct path is executed.
However as soon as I change the value of element.toObserve nothing is happening and the subscription seems to have no effect anymore.
Solution
Doing a subscribe into a subscribe is not recommended. I would rather create an operators chain to your subject and subscribe to it:
If you want to perform some side effects in your components depending on a specific property in your stream, you can use the do operator:
interface Test {
required: boolean;
toObserve: boolean;
}
class TestClass implements OnInit {
@Input() subject: Subject<Test>;
ngOnInit() {
this.registerHandlers().subscribe();
}
registerHandlers() {
return this.subject
.filter(element => element.required)
.do(next => {
if (next.toObserve) {
// DO SOMETHING
} else {
// DO SOMETHING ELSE
}
});
}
}
Answered By - Quentin Fonck
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.