swift - 关于 RxSwift 中 flatMapLatest 的困惑

标签 swift functional-programming reactive-cocoa rx-swift

我学习了 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/

相关文章:

swift - 我可以使用@_silgen_name 来公开不是 Swift 函数的 [Objective-]C 或 C++ 符号吗?

ios - [iOS Swift 4]如何支持 View Controller (模态和推送)

functional-programming - 惰性序列中 "Lose your head"的解释

ios - 返回值类型为CGFloat时如何使用ReactiveCocoa发送Keypath

ios - 如何将 Signal<Bool, NoError> 绑定(bind)到 Reactive Cocoa 4 中 UIButton 的启用属性

ios - 在 Swift 中调整 CAShapeLayer 的大小

ios - 使用swift对日期进行排序

Java8 实例化谓词

Haskell Lambda 帮助 - 从 lambda 术语输入中拆分术语

ios - ReactiveCocoa 中的内存管理