Observable.combine在kotlin中的最新类型推断

时间:2017-03-10 18:52:54

标签: android kotlin rx-java2 rx-binding

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

我有简单的登录界面,默认情况下禁用“登录”按钮,我只想在用户名和密码的edittext字段不为空时启用该按钮。

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中第三个参数的类型推断有关,但我没有通过阅读错误消息来正确解决问题: Type Inference issue

2 个答案:

答案 0 :(得分:34)

您的问题是编译器无法确定要调用哪个覆盖combineLatest,因为多个覆盖都有功能接口作为其第三个参数。您可以使用SAM构造函数显式转换,如下所示:

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

聚苯乙烯。感谢您提出这个问题,它帮助我弄清楚我最初错误地认为这个问题是同样的问题,我现在也用这个解决方案更新了。 https://stackoverflow.com/a/42636503/4465208

答案 1 :(得分:27)

您可以使用RxKotlin为SAM模糊问题提供辅助方法。

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

如您所见,在RxKotlin中使用Observables代替Observable