简体   繁体   中英

Subscription using Driver with RxSwift

I have a question about RxSwift and the use with Driver.

I tried only with this pattern

        loginButton.rx_tap
             .doOn({[unowned self] _ in
                 self.loginButton.enabled = false
             })
             .debug()
             .flatMap({[unowned self] in self.loginViewModel.login() })
             .subscribeNext({ [weak self] login  in
               // Custom code
        })
        .addDisposableTo(disposeBag)

So all starts with a tap to a button...but If I can try to start in this way:

    let contractCode = Variable(contractDetail.contractCode).asDriver()
    viewModel = viewModel(provider: apiProvider! as! RxMoyaProvider<APIProvider>, contractCode: contractCode)
    _ = viewModel?.getStatus()
    .subscribeNext({ data in
        print(data)
        guard data?.result == 1 else {
            // ALERT
            return;
        }
        // Custom code
    })

Where contractDetail.contractCode is a String, contractCode in the viewModel is a Driver. It subscribes to it but doesn't fires onNext so subscribeNext doesn't get called. Can you help me? what is wrong about this approach? Thanks

You mean this part didn't fire onNext: Variable(contractDetail.contractCode).asDriver() ? If yes, how you change the value of your contractCode? If you do this:

// binding
Variable(contractDetail.contractCode).asDriver()./* more binding */
// change value (contractCode is a simple string)
contractDetail.contractCode = "new value of contract"

It will not work, because Variable don't observe given value, so you have to change value property of actual Variable:

// create variable
let variable = Variable(contractDetail.contractCode)
// binding
variable.asDriver()./* more binding */
// change value of variable
variable.value = "new value of contract"

In this case new value will cause onNext event on subscribers of that Variable.

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