I'm trying to use RxJava to perform a validation on a EditText when I click a button but I'm having a hard time moving the validation to the ViewModel which would make testing much easier. I'm using RxBindings from Jake Wharton to get the UI input and RxJava2's Flowable.combineLatest with a PublishSubject to trigger the Flowable when I click a button on a AlertDialog. Here's what I got so far:
private Flowable<CharSequence> projectTitleObservable;
private final PublishSubject<CharSequence> createProjectClicked = PublishSubject.create();
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity();
View dialogView = LayoutInflater.from(context).inflate(R.layout.new_project, null);
ButterKnife.bind(this, dialogView);
projectTitleObservable = RxTextView.textChanges(projectNameEditText).toFlowable(BackpressureStrategy.LATEST);
ConnectableFlowable <CharSequence> connectableFlowable = Flowable.combineLatest(createProjectClicked.toFlowable(BackpressureStrategy.LATEST), projectTitleObservable, (ignored, title) -> {
boolean validTitle = !TextUtils.isEmpty(title);
if (!validTitle) {
projectNameEditText.setError("Project must have a name");
}
Timber.d("Hey, lambdas work! Look -> " + title);
return title;
})
.publish();
connectableFlowable.subscribe(test -> Timber.d(test.toString()));
return new AlertDialog.Builder(context)
.setTitle("Add new Project")
.setView(dialogView)
.setPositiveButton(android.R.string.ok, (dialogInterface, i) -> {
Timber.d("Ok clicked!");
createProjectClicked.onNext("It works!");
})
.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> Timber.d("Cancel clicked!"))
.create();
}
I'm only publishing and subscribing on the same place to make sure it actually works before moving the ConnectableFlowable to the ViewModel. The only log I got was the "Ok clicked!" which for me it means it was never subscribed. Any idea on why it's not subscribing?