I've started learning RxSwift, but can't understand some moments. I have to create a button after performing a request. Like this:
textField.rx.text
.flatMapLatest { text in
return performURLRequest(text)
}
.subscribe(onNext: { request in
// Create a button
let button = UIButton()
button.rx.tap
.subscribe({ _ in
// Action
}).disposed(by: self.disposeBag)
self.view.addSubview(button)
})
.disposed(by: disposeBag)
How can I avoid nesting subscribe calls? Because of this code smell.
You could avoid nested subscription by using flatMap
e.g. (orEmpty is optional)
textField.rx.text.orEmpty
.flatMapLatest { text in
return performURLRequest(text)
}
.flatMap { request -> Observable<Void> in
// Create a button
let button = UIButton()
self.view.addSubview(button)
return button.rx.tap.asObservable()
}
.subscribe({ _ in
// Action
}).disposed(by: self.disposeBag)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With