Shared RxJS subject for bidirectional data binding in Angular 2

后端 未结 2 1007
不思量自难忘°
不思量自难忘° 2021-01-19 19:38

I have a singleton service for app settings

class Setting {
  get foo() {
    return storage.get(\'foo\');
  }

  set foo(val)
    storage.set(\'foo\', val);         


        
2条回答
  •  礼貌的吻别
    2021-01-19 19:40

    It was really easy to get a subject with side effects by extending AnonymousSubject (a class for Subject.create(...) factory). Resulting subject gets destination and source properties that hold original subject and observable.

    class FooSharedSubject extends AnonymousSubject {
        constructor() {
            const subject = new BehaviorSubject('');
    
            const observable = subject.asObservable()
            .mergeMap((value) => promisedStorage.get('foo'))
            .publishReplay(1)
            .refCount();
    
            super(subject, observable);
        }
    
        next(value): void {
            promisedStorage.set('foo', value)).then(
                () => this.destination.next(value),
                () => this.destination.error(value)
            );
        }
    }
    

提交回复
热议问题