Combine操作符Mapping示例


2天前 7次点击 来自 移动端

标签: Swift

Mapping 映射

xxx / tryXXX 是成对的Operator,2者唯一的区别是tryXXX可主动抛出自定义异常,而xxx由Combine框架发送异常,一旦pipline接收到Error,将以.failure事件结束

scan / tryScan

数据累积,可记忆一个单位数据

_ = [3, 4, 5]
    .publisher
    .scan(0) { acc, current -> Int in
        acc + current
    }
    .sink(receiveValue: { someValue in
        print(someValue)
    })

map/tryMap

scan收集数据,map和tryMap映射数据,转换数据状态

_ = [3, 4, 5]
    .publisher
    .map { intValue -> String in
        String(intValue)
    }
    .sink(receiveValue: { someValue in
        print(someValue)
    })

flatMap

flatMap能够把上游输出的值转换为一个新的pulisher,flatMap的典型应用场景是网络请求JSON数据并映射成本地模型

struct Student: Decodable {
    let name: String
}

let json = """
[{
"name": "A"
},
{
"name": "B"
},
{
"name": "C"
}]
"""

_ = Just(json)
    .flatMap { value in
        Just(value.data(using: .utf8)!)
            .decode(type: [Student].self, decoder: JSONDecoder())
            .catch { _ in
                Just([Student(name: "Unknown")])
            }
    }
    .sink(receiveCompletion: { _ in
        print("Finished")
    }, receiveValue: { someValue in
        print(someValue)
    })

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1