Ralph Bergmann
Ralph Bergmann

Reputation: 3076

Get current value of RxJava Observable

In my UI I have a RadioGroup with 3 RadioButtons and a "normal" Button.

When the user clicks on the Button I want to read the selected RadioButton to do something with it.

RxView.clicks(button)
      .flatMap(x -> RxRadioGroup.checkedChanges(radioGroup_timer))
      .map(view -> {
          switch (view) {
              case R.id.radioButton_10sec_timer:
                  return 10;
              case R.id.radioButton_20sec_timer:
                  return 20;
              default:
                  return DEFAULT_TIMER;
          }
      })
    .subscribe(duration -> Timber.i("duration: %,d",duration));

It works so far but now every time the user selects an other RadioButton I get a new log message.

Is there a way to read the current selected RadioButton without subscribing for changes?

Upvotes: 4

Views: 1388

Answers (1)

Crocodilys
Crocodilys

Reputation: 96

do smthing like this

RxView.clicks(button)
      .withLatestFrom(RxRadioGroup.checkedChanges(radioGroup_timer), (click, checked) -> checked)
      .map(...)

withLatestFrom will take only LATEST element from the checkedChanges stream, and flatMap will create new Observable, that will emits ALL items from this stream

Upvotes: 3

Related Questions