问题描述
let
操作符的示例和解释(https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/let.md) 不清楚.任何人都有一个很好的例子/解释 let
操作符是如何工作的,我们应该在什么时候使用它?
The example and explanation of the let
operator (https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/let.md) is not clear. Anyone has a good example/explanation how the let
operator works, and when we should use it?
推荐答案
&tldr;
这是一个方便的功能,能够划分逻辑并将其注入管道.
It is a convenience function for being able to compartmentalize logic and inject it into a pipeline.
更长的解释
来源可能是最权威的解释.它实际上只是传递一个使用源 Observable
调用的函数.
The source is probably the most definitive explanation. It is really just passing a function which gets called with a source Observable
.
Rx.Observable.prototype.let = function(fn) {
return fn(this);
}
这样做的用处在于,我们可以创建或预定义您希望为多个源重复使用的管道.考虑 Rx 的一个常见比喻,即反应式搜索栏:
The utility of this is that we can create or pre-define a pipeline that you want to reuse for multiple sources. Consider a common trope for Rx, the reactive search bar:
// Listen to a key up event on the search bar
// and emit the value of the search
Rx.Observable.fromEvent(searchBar, 'keyup', e => e.target.value)
// Don't search too eagerly
.filter(text => text.length > 3)
.debounceTime(500)
//Search logic
.flatMap(text => $.getJSON(`my/search/api?q=${text}`))
.flatMap({results} => results)
//Handler
.subscribe(appendToList);
以上内容应该对如何创建管道的结构有一个基本的了解.如果我们想尝试抽象一些这种逻辑来清理代码或能够在其他地方使用它可能有点棘手,因为这通常意味着创建一个新的运算符(这有其自身的问题).
The above should give a basic sense of the structure of how a pipeline might be created. If we wanted to try and abstract some of this logic either to clean up the code or to be able to use it elsewhere it can be a little tricky, because it usually means creating a new operator (and that has its own headaches).
解决方案是一种相对简单的方法,将通用逻辑拉入一个函数中,该函数可以传递源Observable
,并返回一个应用该逻辑的新Observable
.
The solution is a relatively simple approach of pulling common logic into a function that can be passed a source Observable
and will return a new Observable
with that logic applied.
所以上面可能会变成:
//Defined in pipelines.js
function filterBuilder(minText, debounceTime) {
return (source) =>
source.filter(text => text.length > minText)
.debounce(debounceTime);
}
function queryBuilder(baseUrl) {
return (source) =>
source.flatMap(text => $.getJSON(`${baseUrl}?q=${text}`))
.flatMap({results} => results);
}
//In your application code
Rx.Observable.fromEvent(searchBar, 'keyup', e => e.target.value)
.let(filterBuilder(3, 500))
.let(queryBuilder('my/search/api'))
.subscribe(appendResults);
这篇关于如何使用 Rx.Observable.prototype.let 操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!