natecraft1
natecraft1

Reputation: 2846

RxSwift exit from observable chain if text is empty

I'm having trouble understanding the way to early exit from an observable sequence if I don't have the necessary info. Here's a simplified example...

@IBOutlet weak var myTextField: UITextField!
...
myButton.rx.tap. // stop here if textField is nil or empty
.flatMap { API.fetchMyList() }
.subscribe...

Upvotes: 0

Views: 2101

Answers (1)

tomahh
tomahh

Reputation: 13661

You’ll want to transform your observable chain to include the content of the text field, and then filter out the values you are not interested in. The operator withLatestFrom will pull values from another observable into the current chain.

@IBOutlet weak var myTextField: UITextField!

myButton.rx.tap
.withLatestFrom(myTextField.rx.text)
.filter { $0 != nil && $0?.isEmpty == false }
.flatMapLatest { // here $0 is the value of the text field
  API.fetchMyList($0) 
}
.subscribe...

As a side note, you’ll probably want to use flatMapLatest in lieu of flatMap, so that old requests get canceled if another tap of button occurs.

Upvotes: 2

Related Questions