简体   繁体   中英

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.

You could avoid nested subscription by using flatMap eg (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)

I can confirm nested subscribes are a no-no.

You can use the switchMap operator in a pipe .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM