Search code examples
androidrx-java2rx-binding

How do I collect form inputs, evaluate, and conditionally go to another view or post data using rxJava


I have a form with two inputs setup with rx-binding observables, and I have the validation working to enable/disable my submit.

What I'm struggling to think through is form submittal. When the submit is clicked. I need to grab the latest values from form inputs. Then evaluate to see if I need more info, which results in a call back to the view to go to a different page. If more info is not needed then I need to do a post with retrofit.

I'm not sure the proper way to grab the latest form values (combineLatest, withLatestFrom, zip?) and how to conditionally call back to the view vs the retrofit post, particularly what should be handled by operators directly, vs the combine callback from combineLatest, vs the subscribe callback.

Thanks for any assistance.


Solution

  • Here is what I came up with. It seems to work. If you see any gotchas, or things I could do better, please respond.

    private void handleMenuItemClicks() {
        mCompositeDisposable.add(view.menuItemClicks().subscribe(menuItem -> {
            if (menuItem.getItemId() == R.id.action_submit) {
                mCompositeDisposable.add(Observable.combineLatest(
                        view.nameTextChanges(),
                        view.msgTextChanges(),
                        (CharSequence nameTxt, CharSequence msgTxt) -> {
                            return new CharSequence[] {nameTxt, msgTxt};
                        }
                    ).filter(values -> {
                        boolean isParticipant = participant != null && values[0].toString().equals(participant.toString());
                        if (!isParticipant) {
                            view.navigateToInfo();
                        }
                        return isParticipant;
                    }).flatMap(values -> myService.createItem(
                        participant.participantNumber, values[0].toString(), values[1].toString())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()).toObservable()
                    ).subscribe(response -> {
                        view.showSuccess();
                    })
                );
            }
        }));
    }