【问题标题】:RXJS Caching system with "next" method带有“next”方法的 RXJS 缓存系统
【发布时间】:2019-04-23 15:18:33
【问题描述】:

我可以用 BehaviourSubject 构建缓存系统:

class MessagesStore {
     constructor() {
         timer(0, 60 * 1000).pipe(
             switchMap(_ => this.messagesService.getMessages())
         ).subscribe(ms => this.subject.next(ms))
     }

     get messages$() {
         return this.subject.asObservable()
     }
}

但是对于这个解决方案,当任何组件不订阅消息时,消息将被刷新$。所以我可以建立没有主题的缓存:

get messages$() {
    return timer(0, 60 * 1000).pipe(switchMap(_ => 
        this.messagesService.getMessages()), shareReplay(1))
}

readMessages() {
    this.subject.value.forEach(ms => ms.read = true)
    this.subject.next(subject.value)
}

但现在我不能使用“下一个”方法

是否可以有主题但有自动退订源或类似的东西?

编辑:我想出了:

    let customUpdate: Subject<number> = new Subject();
    let lastNumber = 0;
    const fapy = interval(1000).pipe(
      tap(data => console.log('updater', data)), 
      merge(customUpdate),
      publishReplay(1),
      refCount(),
      tap(data => lastNumber = data)
    )
    const sub1 = fapy.subscribe(data => console.log('receirver1', data))
    const sub2 = fapy.subscribe(data => console.log('receirver2', data))
    let sub3

    setTimeout(_ => customUpdate.next(lastNumber + 1), 3000)
    setTimeout(_ => sub1.unsubscribe(), 3000)
    setTimeout(_ => sub2.unsubscribe(), 5000)
    setTimeout(_ => {sub3 = fapy.subscribe(data => console.log('receirver3', data))}, 7000)
    setTimeout(_ => {sub3.unsubscribe()}, 10000)

我觉得自己像 rxjs 大师 :d

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    您可以使用 lodash 库来比较您的当前值和刚刚传入的值,并在两者不同时更新值

    类似这样的:

    timer(0, 60 * 1000).pipe(switchMap(_ => this.messagesService.getMessages())
        .subscribe(ms => this.cache(this.subject, ms))
    
    get messages$() {
        return this.subject.asObservable()
    }
    
    public cache(subject: BehaviorSubject<any>, next: any): void {
            if (!_.isEqual(subject.getValue(), next)) {
                subject.next(next);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-04
      • 2013-04-06
      • 2019-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多