【问题标题】:Performs operations on some observables on trigger observables - RxJS在触发器可观察对象上对某些可观察对象执行操作 - RxJS
【发布时间】:2016-01-21 05:01:05
【问题描述】:

我仍在尝试使用 RxJS 和 React Native。我正在构建一个带有 id TextInput、密码 TextInput 和登录按钮的登录屏幕,它们都通过 jsx 附加了一个单独的回调处理程序(因此我无法使用 RxJS 的“fromEvent”API 创建可观察对象)。

在 componentWillMount 中,我为 id 文本更改、密码文本更改和单击处理程序创建了一个主题。

//In id text change handler
this.idStream.onNext(newId);

//In password text change handler
this.passwordStream.onNext(newPassword);

//In click handler
this.buttonClickStream.onNext(null); //null since value is not important

我只希望在按钮 ID 和密码不是空字符串并且单击按钮时触发 API 请求。

在componentWillMount我试过

var subscription = this.buttonClickStream
                       .combineLatest(this.idStream, this.passwordStream, function(click, id, password) {
    return {
         id: id,
         password: password
    };
})
.filter(credentials => {return credentials.id.length > 0 &&
                               credentials.password.length > 0;}
.subscribe(function(credentials) {
    console.log('fire API request with credentials');
});

但是问题在于,由于我使用的是 combineLatest,因此不仅在单击按钮时触发 api,而且每次更改 id 或密码时都会触发 api(前提是它们通过了过滤器)。我错过了什么?

谢谢!

【问题讨论】:

    标签: javascript reactjs react-native rxjs frp


    【解决方案1】:

    我认为您可以使用Rx.withLatestFrom 代替combineLatest。它仅在源 observable 触发并将您传递的 observable 最后发出的值作为参数时触发。

    参照。 http://rxmarbles.com/#withLatestFrom

    【讨论】:

    • 就是这个!谢谢!
    • 就像一个后续问题,在上面的示例中,单独处理订阅是否足够?或者我也应该“完成”我创建的每个主题?
    • 不确定,也许您可​​以将主题与常规可观察对象的生命周期作为另一个问题。
    猜你喜欢
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2016-09-12
    • 2020-12-22
    • 2020-02-11
    • 1970-01-01
    相关资源
    最近更新 更多