2017-09-14 41 views
0

你好吗。我是Rxjs的新手。我不确定如何合并来自不同事件的观察值。我综合Rxjs与Vue.js如何使Rxjs中的多个事件可观察?

export default { 
    name: 'useraside', 
    data: function() { 
    return { 
     searchKey: '', 
     isPublic: true 
    } 
    }, 
    components: { 
    User 
    }, 
    subscriptions() { 
    return { 
     // this is the example in RxJS's readme. 
     raps: this.$watchAsObservable('searchKey') 
     .pluck('newValue') 
     // .filter(text => text.length > 1) 
     .debounceTime(500) 
     .distinctUntilChanged() 
     .switchMap(terms => fetchRaps(terms, this.userdata._id, this.isPublic)) 
     .map(formatResult) 
    } 
    } 
} 

现在事件来自searchKey变化,现在我想订阅同样观察到当isPublic值的变化。 所以我想每当searchKey更改或isPublic更改时都会得到说唱。 谢谢。

+2

只是使用合并操作;)http://reactivex.io/rxjs/class/es6 /Observable.js~Observable.html#static-method-merge – Maxime

+0

谢谢。现在正在工作 –

回答

1

您可以使用merge运算符,并在您的switchMap中继续使用this.isPublic,正如Maxime在评论中所建议的那样。

但我宁愿去一个很好的纯数据流,你听两个值,并在你的处理程序中使用它们。像

Rx.Observable.combineLatest(
    this.$watchAsObservable('searchKey').pluck('newValue'), 
    this.$watchAsObservable('isPublic').pluch('newValue'), 
    ([searchKey, isPublic]) => ({ searchKey, isPublic }) 
) 
.dedounceTime(500) 
.distinctUntilChanged() 
.switchMap(({ searchTerm, isPublic }) => fetchRaps(searchTerm, this.userdata._id, isPublic)) 

或事件更好的事情是,你可以将初始数据结构更改为类似:

data: function() { 
    return { 
     searchConfig: { 
     searchKey: '', 
     isPublic: true 
     } 
    } 
    }, 

,那么你可以删除combineLatest,仅看searchConfig财产。

此实现的好处是您的数据流是纯粹的,并且不依赖于任何外部上下文(不需要this.isPublic)。每个依赖项都在数据流开始时显式声明。

如果你想走得更远,你还可以观看userdata和明确地传递下来的数据流:)