I am new to RxSwift and RxCocoa I need to any advice for learning
After result of Checking Id Validation, expect no word in label
But it is updating label and no entering in break point at bind function
What’s problem my code…?
var disposeBag: DisposeBag = DisposeBag()
let viewModel = ViewModel()
override func viewDidLoad() {
super.viewDidLoad()
let input: Signal<String> = userIDTextField.rx.text.orEmpty
.asSignal(onErrorSignalWith: .empty())
let output: Driver<String> = viewModel.bind(input)
disposeBag.insert(
output.drive(userIDLabel.rx.text)
)
}
struct ViewModel {
func checkUserIDFromDB(id: String) -> Signal<Bool> {
return .just(false).asSignal()
}
func bind(_ input: Signal<String>) -> Driver<String> {
let validState = input
.map { _ in self.checkUserIDFromDB(id:)}
.withLatestFrom(input)
return validState.asDriver(onErrorDriveWith: .empty())
}
}
This line:
.map { _ in self.checkUserIDFromDB(id:)}produces aSignal<(String) -> Signal<Bool>>which is likely not what you wanted.I'm going to assume that the goal here is to pass the entered string to the network request and wait for it to emit. If it emits
truethen emit the string to the label, otherwise do nothing...Further, let's simplify things by using the
Observabletype instead of Signals and Drivers:The biggest concern I have with this code is what happens if the user continues to type. This will fire after every character the user enters which could be a lot of network requests, the
flatMapLatestwill cancel ongoing requests that are no longer needed, but still... Consider putting adebouncein the stream to reduce the number of requests.Learn more about the various versions of
flatMapfrom this article.Edit
In response to your comment. In my opinion, a ViewModel should not be dependent on RxCocoa, only RxSwift. However, if you feel you must use Driver, then something like this would be appropriate:
Using
Signaldoesn't make much sense in this context.