Optional Observables in combineLatest

偶尔善良 提交于 2021-02-08 19:43:14

问题


As definied combineLatest in rx emites only if all values have changed at least once.

(so long as each of the source Observables has emitted at least one item)

I use it to manipulate views within my android views. For example, I enable a call to action button as soon as all observables emitted a valid value. Otherwise I disable it.

    Observable.combineLatest(
            toObservable(email),
            toObservable(username),
            toObservable(status),
            toObservable(phonenumber),
            toObservable(birthdate),
            Function5<String, String, String, String, Date, Boolean> { email, username, status, phonenumber, birthdate ->
                validator?.checkEmail(email) ?: true
                // and much more...
            }
    ).subscribeBy { ctaEnabled.set(it) }

With that snippet the ctaEnabled is only set to true if all values at least changed one. Because Function5 is only called if all Observables have emitted at least 1 item.

BUT, the field for status and birthdate are optional and must not be filled. Because all ObservableFields are initialized with null and can not explicitly set to null (not allowed in rxjava 2) status and birthday are not emitted when the user does not type text into it.

val status: ObservableField<String> = ObservableField()
val phonenumber: ObservableField<String> = ObservableField()
val birthdate: ObservableField<Date> = ObservableField()
// ... and so on

I considered to use .startWith("") which solves the problem for the string Observables because all string Observables emit at least an empty string. But I can't use this solution for the Date field because it is nullable.

Maybe combineLatest is not the operation I am searching for but I can't find a proper way to handle the optional observables.

Best regards & thanks, Moritz

来源:https://stackoverflow.com/questions/47431357/optional-observables-in-combinelatest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!