为了账号安全,请及时绑定邮箱和手机立即绑定

RxJS - 创建自动完成的 Observable,首先从缓存返回数据,然后从服务器返回

RxJS - 创建自动完成的 Observable,首先从缓存返回数据,然后从服务器返回

慕沐林林 2022-06-09 17:07:26
我发现这篇文章解释了我如何使用 RxJs 为自动完成创建一个 observable: https ://blog.strongbrew.io/building-a-safe-autocomplete-operator-with-rxjsconst autocomplete = (time, selector) => (source$) =>  source$.pipe(    debounceTime(time),    switchMap((...args: any[]) =>       selector(...args)        .pipe(            takeUntil(                source$                    .pipe(                        skip(1)                    )            )        )    )  )        term$ = new BehaviorSubject<string>('');  results$ = this.term$.pipe(        autocomplete(1000, (term => this.fetch(term)))    )我想通过首先从本地存储返回数据并将其显示给用户然后继续到服务器获取数据来改进这个自动完成的可观察对象。从服务器返回的数据不会替换本地存储的结果,而是添加到本地存储中。如果我在每次用户键入时都正确理解它,那么 observable 应该发出两次。如何以最有效的方式构建它?
查看完整描述

2 回答

?
芜湖不芜

TA贡献1796条经验 获得超7个赞

我认为你可以利用startWith.


const term$ = new BehaviorSubject('');

const localStorageResults = localStorage.getItem(''); // Map it into the same shape as results$ but the observable unwrapped

const results$ = term$

    .pipe(

        startWith(localStorageResults),

        debounceTime(1000),

        switchMap(term => 

            getAutocompleteSuggestions(term)

                .pipe(

                    takeUntil(

                        //skip 1 value

                        term$.pipe(skip(1))

                    )


                )

            )

        )

    )

你可能不得不修改它,我不确定它是否会很好,debounceTime但这是一个想法。


查看完整回答
反对 回复 2022-06-09
?
慕哥6287543

TA贡献1831条经验 获得超10个赞

所以在处理了几个小时之后,我发现解决方案非常简单:


        autocomplete(1000, (term => new Observable(s => {

          const storageValue = this.fetchFromStorage(term);

          s.next(storageValue);

          this.fetchFromServer(term)

            .subscribe(r => s.next(r));

        })))


查看完整回答
反对 回复 2022-06-09
  • 2 回答
  • 0 关注
  • 146 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号