【问题标题】:Observable.combineLatest type inference in kotlinkotlin 中的 Observable.combineLatest 类型推断
【发布时间】:2017-08-01 05:35:28
【问题描述】:

我在我的项目中使用 RxJava2、Kotlin-1.1 和 RxBindings。

我有一个简单的登录屏幕,默认禁用“登录”按钮,我只想在用户名和密码编辑文本字段不为空时启用该按钮。

LoginActivity.java

Observable<Boolean> isFormEnabled =
    Observable.combineLatest(mUserNameObservable, mPasswordObservable,
        (userName, password) -> userName.length() > 0 && password.length() > 0)
        .distinctUntilChanged();

我无法将上述代码从 Java 翻译成 Kotlin:

LoginActivity.kt

class LoginActivity : AppCompatActivity() {

  val disposable = CompositeDisposable()

  private var userNameObservable: Observable<CharSequence>? = null
  private var passwordObservable: Observable<CharSequence>? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_login)
    initialize()
  }

  fun initialize() {
    userNameObservable = RxTextView.textChanges(username).skip(1)
        .debounce(500, TimeUnit.MILLISECONDS)
    passwordObservable = RxTextView.textChanges(password).skip(1)
        .debounce(500, TimeUnit.MILLISECONDS) 
  }

  private fun setSignInButtonEnableListener() {
    val isSignInEnabled: Observable<Boolean> = Observable.combineLatest(userNameObservable,
        passwordObservable,
        { u: CharSequence, p: CharSequence -> u.isNotEmpty() && p.isNotEmpty() })
  }
}

我认为这与combinelatest 中第三个参数的类型推断有关,但通过阅读错误消息我没有正确解决问题:

【问题讨论】:

    标签: android kotlin rx-java2 rx-binding


    【解决方案1】:

    您的问题是编译器无法确定要调用 combineLatest 的哪个覆盖,因为多个具有功能接口作为它们的第三个参数。您可以使用这样的 SAM 构造函数进行显式转换:

    val isSignInEnabled: Observable<Boolean> = Observable.combineLatest(
            userNameObservable,
            passwordObservable,
            BiFunction { u, p -> u.isNotEmpty() && p.isNotEmpty() })
    

    附言。感谢您提出这个问题,它帮助我发现我最初对这个问题错了,结果证明是同一个问题,我现在也用这个解决方案更新了这个问题。 https://stackoverflow.com/a/42636503/4465208

    【讨论】:

    • 花了我这么长时间才弄明白。
    • 这个link 可能对这个答案有帮助。
    【解决方案2】:

    您可以使用RxKotlin,它为您提供解决 SAM 歧义问题的辅助方法。

    val isSignInEnabled: Observable<Boolean> = Observables.combineLatest(
        userNameObservable,
        passwordObservable)
        { u, p -> u.isNotEmpty() && p.isNotEmpty() })
    

    如您所见,在 RxKotlin 中使用 Observables 而不是 Observable

    【讨论】:

    • 你救了我的命!谢谢。
    猜你喜欢
    • 2018-08-21
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多