25

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

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

登录活动.java

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

我无法将上述代码从 Java 转换为 Kotlin:

登录活动.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() })
  }
}

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

4

2 回答 2

41

Your issue is that the compiler can't figure out which override of combineLatest to call, because multiple ones have functional interfaces as their third parameter. You can make the conversion explicit with a SAM constructor like this:

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

Ps. Thanks for asking this question, it helped me figure out that I was initially wrong about this one that turns out to be the same problem, which I've now updated with this solution as well. https://stackoverflow.com/a/42636503/4465208

于 2017-03-10T19:22:12.967 回答
40

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

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

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

于 2017-11-05T02:40:30.883 回答