• [AngularJS + RxJS] Search with RxJS


    When doing search function, you always need to consider about the concurrent requests. 

    AEvent ----(6s)---> AResult

    ------(100ms)-------

    BEvent -----(1s)---> BResult

    It means A event needs to take 6 seconds to get the result, but B only need 1 second, in the between there is 100ms. 

    So B result will appear on the DOM first, but later will be overwritten by A result once A finished. 

    To overcome this problem, we can use RxJS:

    class HelpSearchCtrl {
        constructor(HelpSearchService, $scope, $log) {
            this.HelpSearchService = HelpSearchService; 
            this.searchTerm = null;
            this.$log = $log;
            this.$scope = $scope;
    
            let listener = Rx.Observable.create( (observe)=>{
               
                 this.$scope.$watch( ()=>{
                    return this.searchTerm;
                 }, ()=>{
                     observe.onNext(this.searchTerm);
                 })
            })
            .debounce(500)
            .flatMapLatest( (searchTerm)=> {
                return Rx.Observable.fromPromise(this.doSearch(searchTerm));
            }).subscribe();
    
            this.$scope.$on('$destory', ()=>{
                this.$log.debug('cancelled!');
                listener.dispose();
            })
        } 
    
        doSearch(searchTerm) {
            return this.HelpSearchService.searchForContent(searchTerm);
        }
    }
    
    const clmHelpSearchDirective = () => {
        return {
            restrict: 'EA',
            scope: {},
            replace: true,
            template: require('./help-search.html'),
            controller: HelpSearchCtrl,
            controllerAs: 'vm',
            bindToController: true
        }
    };
    
    export default (ngModule)=> {
        ngModule.directive('clmHelpSearch', clmHelpSearchDirective);
    }
  • 相关阅读:
    4.2. 入门案例
    4.1. Scrapy配置安装
    4. Scrapy框架
    2.6. 案例:使用BeautifuSoup4的爬虫
    2.03_01_Python网络爬虫urllib2库
    2.06_Python网络爬虫_正则表达式
    2.04_Python网络爬虫_Requests模块
    2.03_Python网络爬虫Http和Https
    TCP协议的三次握手
    从零开始搭建VUE项目
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5185266.html
Copyright © 2020-2023  润新知