Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting subscribe calls in RxSwift

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.

like image 428
Artem Krachulov Avatar asked Jan 02 '23 01:01

Artem Krachulov


1 Answers

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)
like image 82
christopher.online Avatar answered Jan 12 '23 03:01

christopher.online