RxJS - 创建自动完成 Observable,首先 Returns 来自缓存然后来自服务器的数据
RxJS - Create Auto-Complete Observable That First Returns Data From Cache And Then From Server
我发现这篇文章解释了如何使用 RxJs 创建一个自动完成的可观察对象:
https://blog.strongbrew.io/building-a-safe-autocomplete-operator-with-rxjs
const 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 应该发出两次。
如何以最有效的方式构建它?
亲切的问候,
塔尔休米
我认为你可以利用 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
但这是一个主意。
所以在处理了几个小时之后,我发现解决方案非常简单:
autocomplete(1000, (term => new Observable(s => {
const storageValue = this.fetchFromStorage(term);
s.next(storageValue);
this.fetchFromServer(term)
.subscribe(r => s.next(r));
})))
我发现这篇文章解释了如何使用 RxJs 创建一个自动完成的可观察对象: https://blog.strongbrew.io/building-a-safe-autocomplete-operator-with-rxjs
const 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 应该发出两次。
如何以最有效的方式构建它? 亲切的问候, 塔尔休米
我认为你可以利用 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
但这是一个主意。
所以在处理了几个小时之后,我发现解决方案非常简单:
autocomplete(1000, (term => new Observable(s => {
const storageValue = this.fetchFromStorage(term);
s.next(storageValue);
this.fetchFromServer(term)
.subscribe(r => s.next(r));
})))