Last active
April 21, 2019 01:39
-
-
Save cartant/8b647725bdc705e6dbcb8f36e22ad60a to your computer and use it in GitHub Desktop.
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
| import { Component, Input, OnInit, OnDestroy } from "@angular/core"; | |
| import { debounceTime, distinctUntilChanged, switchMapTo, takeUntil } from "rxjs/operators"; | |
| import { observe } from "rxjs-observe"; | |
| @Component({ | |
| selector: "some-component", | |
| template: "<span>Some useless component that writes to the console</span>" | |
| }) | |
| class SomeComponent implements OnInit, OnDestroy { | |
| @Input() public name: string; | |
| constructor() { | |
| const { observables, proxy } = observe(this as SomeComponent); | |
| observables.ngOnInit.pipe( | |
| switchMapTo(observables.name), | |
| debounceTime(400), | |
| distinctUntilChanged(), | |
| takeUntil(observables.ngOnDestroy) | |
| ).subscribe(value => console.log(value)); | |
| return proxy; | |
| } | |
| ngOnInit() {} | |
| ngOnDestroy() {} | |
| } |
Btw, that's a great approach!
e.g. right now I have the use case where I have foo$ Observable and I need to re-subscribe to a different store.selector based on a fooId change e.g. this is what I have right now:
export class FooComponent {
private fooIdInternal: string;
foo$ = new ReplaySubject<SingleFoo>(1);
@Input()
set fooId(fooId: string) {
this.fooIdInternal = fooId;
// Done through Subject to avoid memory leaks on fooId changes.
this.store.pipe(select(getSingleFoo(fooId))).subscribe(this.foo$);
}
get fooId(): string {
return this.fooIdInternal;
}
constructor(private readonly store: Store<{}>) {}
}with rxjs-observe this will change to:
class FooComponent implements OnInit, OnDestroy {
@Input() fooId: string;
foo$: Observable<SingleFoo>;
constructor(private readonly store: Store<{}>) {
const { observables, proxy } = observe<FooComponent>(this);
foo$ = observables.fooId.pipe(
switchMap(fooId => this.store.pipe(select(getSingleFoo(fooId)))),
);
}Much cleaner!
Hmm ... implementation based on rxjs-observe looks really better. But why do you make presentation component tightly coupled with the store? The component becomes hard to reuse.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey Nicholas, I don't think
return proxy;is necessary. What does that give you?