如何在Observables.combineLatest中收听三个以上的字段

时间:2018-02-22 07:55:35

标签: android kotlin kotlin-android-extensions rx-kotlin

我有代码使用 Observables.combineLatest

正好收听三个字段
Observables.combineLatest(text_name.asObservable(),text_username.asObservable(), text_email.asObservable()).subscribe({ t ->
            if (t.first.toString() != currentName || t.second.toString() != currentUsername) {
                startActionMode()
            } else {
                finishActionMode()
            }
        })

但是当我向 Observables.combineLatest 添加另一个参数时,它会出现错误,因为只能传递3个内联参数..

现在我希望在 Observables.combineLatest 的参数列表中传递4个参数..我知道它应该使用数组或列表完成,作为参数传入但对我来说很难使用 Kotlin 计算出来。

帮帮我..先谢谢你..

1 个答案:

答案 0 :(得分:1)

如果要组合3个以上的可观察对象,则需要添加组合功能。你可以做这样的事情。

    Observables.combineLatest(
            first.asObservable(),
            second.asObservable(),
            third.asObservable(),
            forth.asObservable()
    )
    // combine function
    { first, second, third, forth->
        // verify data and return a boolean
        return@subscribe first.toString() != currentName || second.toString() != currentUsername
    }
    .subscribe({ isValid->
                   if (isValid) {
                       startActionMode()
                   } else {
                       finishActionMode()
                   }
               })

在combine函数中,您可以验证数据并返回布尔值。 然后在订阅中,您可以根据该布尔值

执行操作