Chris G.
Chris G.

Reputation: 26004

RxSwift 3 documentation driving, binding and actions

I am having trouble finding my way around in RxSwift. Like now I need to update a UILabel When a UIButton is pressed. My take on this is:

  1. The button needs two emit at det er pressed, and possible map some values two channeling down the stream.
  2. The UILabel needs two subscribe til button.

But I can not find any documentation for RxSwift 3.0 or newer?

Upvotes: 1

Views: 2469

Answers (1)

Shai Mishali
Shai Mishali

Reputation: 9402

RxSwift, in your case, lets you manipulate events from an Observable of one type, into a different type.

In this case you would want to do something like this:

btnButton.rx.tap // This is a ControlEvent<Void> (you can think of it as Observable<Void> for our purposes
    .map { return "Button was Pressed" } // This is now Observable<String>
    .asDriver(onErrorJustReturn: "") // This is now Driver<String>
    .drive(lblText.rx.text)
    .disposed(by: disposeBag)

Lets go through this step by step

  1. You observe taps from the button's tap Observable
  2. For every tap, you map that event to some string
  3. In our case, since we are dealing with UI elements, It's best practice to convert the Observable to a Driver, that ensures emissions happen on the Main Scheduler, along other benefits
  4. We "drive" the label's text with the string we just mapped.

TL;DR this would set the label every time you tap the button, which won't help much since it changes to the same String, but you can apply that technique to map dynamic strings etc.

Good luck on the great journey with RxSwift, and feel free to join the Slack channel, since there's mach more help and ongoing activity there

Upvotes: 3

Related Questions