简体   繁体   English

在RxSwift中嵌套订阅调用

[英]Nesting subscribe calls in RxSwift

I've started learning RxSwift, but can't understand some moments. 我已经开始学习RxSwift,但无法理解一些时刻。 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) 您可以使用flatMap避免嵌套订阅,例如(orEmpty是可选的)

    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 . 您可以在pipe使用switchMap运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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