gpt4 book ai didi

swift - 关于 RxSwift 中 flatMapLatest 的困惑

转载 作者:IT王子 更新时间:2023-10-29 05:24:49 26 4
gpt4 key购买 nike

我学习了 RxSwift 中的示例代码。在文件 GithubSignupViewModel1.swift 中,validatedUsername 的定义是:

validatedUsername = input.username //the username is a textfiled.rx_text
.flatMapLatest { username -> Observable<ValidationResult> in
print("-------->1:")
return validationService.validateUsername(username)
.observeOn(MainScheduler.instance)
.catchErrorJustReturn(.Failed(message: "Error contacting server"))
}
.shareReplay(1)

validateUsername 方法最终调用如下方法:

func usernameAvailable(username: String) -> Observable<Bool> {
// this is ofc just mock, but good enough
print("-------->2:")
let URL = NSURL(string: "https://github.com/\(username.URLEscaped)")!
let request = NSURLRequest(URL: URL)
return self.URLSession.rx_response(request)
.map { (maybeData, response) in
print("-------->3:")
return response.statusCode == 404
}
.catchErrorJustReturn(false)
}

这是我的困惑:

每当我在用户名文本字段中快速输入一个字符时,消息 -------->1:, -------->2: 显示,稍后显示消息 ----- --->3: showed, but only showed one ------>3: 消息。

当我输入字符较慢时,消息-------->1:, -------->2:, -------->3: 依次显示。

但是当我将 flatMapLatest 更改为 flatMap 时,我输入了多少个字符,我将得到相同数量的 ------>3: 消息。

那么 flatMapLatest 在这里是如何工作的呢?

flatMapLatest 如何过滤来自 NSURLResponse 的早期响应?


我读了一些关于 flatMapLatest 的内容,但没有一个能解释我的困惑。

我看到的是这样的:

let a = Variable(XX)
a.asObservable().flatMapLatest(...)

当将a.value 更改为另一个Variable 时,Variable(XX) 不会影响a 的订阅者。

但是 input.username 没有改变,它始终是 testfield.rx_text!那么 flatMapLatest 是如何工作的呢?

最佳答案

TheDroidsOnDroid 的回答对我来说很明确:

FlatMapLatest diagram

Well, flatMap() gets one value, then performs long task, and when it gets the next value, previous task will still finish even when the new value arrives in the middle of the current task. It isn’t really what we need because when we get a new text in the search bar, we want to cancel the previous request and start another. That’s what flatMapLatest() does.

http://www.thedroidsonroids.com/blog/ios/rxswift-examples-3-networking/

您可以使用 Appstore 上的 RxMarbles 应用与运算符(operator)一起玩。

关于swift - 关于 RxSwift 中 flatMapLatest 的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37455901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com