简体   繁体   English

Rxjs 使用 Observable.from() 字符串并防止 Observable 被多次创建

[英]Rxjs using Observable.from() string and prevent Observable being created many times

I have the following function that I'm trying to prevent Observable from being created every time this function is called.我有以下函数,我试图防止每次调用此函数时都创建 Observable。 Basically, this function is called every time the user types something in the search field.基本上,每次用户在搜索字段中键入内容时都会调用此函数。 I know I can create Observable from the event as Observable.fromEvent('button', click) but it would require me make tons of changes to the app.我知道我可以从事件创建 Observable 为 Observable.fromEvent('button', click) 但这需要我对应用程序进行大量更改。 Any help is appreciated.任何帮助表示赞赏。

function search(input) { 
  Observable.from([input])
  .map(value => value)
  .filter(value => value.length >3)
  .debounceTime(300)
  .distinctUntilChanged()
  .switchMap(searchValue => { 
    //ajax call 
    return Promise.resolve(data) 
  }) 
  .subscribe(data => {
    //Do something with the data
  })
}

If you want to use observables, but don't want to create one from an event, you can create a Subject and can call its next method from within your search :如果您想使用 observables,但不想从事件中创建一个,您可以创建一个Subject并可以从您的search调用其next方法:

import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';

var searchSubject = new Subject();
  .filter(value => value.length > 3)
  .debounceTime(300)
  .distinctUntilChanged()
  .switchMap(searchValue => { 
    // ajax call
    return Promise.resolve(data) 
  }) 
  .subscribe(data => {
    // Do something with the data
  });

function search(input) { 
  searchSubject.next(input);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM