Combine操作符Reducing示例


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

标签: Swift

Reducing 缩小

功能上类似Filtering过滤,不同点在于Reducing的目的在于收集数据,使用Reducing可自定义各种数据收集的规则

collect

最简单的使用.collect(3)表示将所有数据按3个一组打包收集

通过.collect(.byTime(q, 1.0))指定时间间隔收集,通过.collect(.byTimeOrCount(q, 1.0, 5))同时指定时间间隔与数量

ignoreOutput

忽略publisher发送的数据

["1", "2", "3"]
.publisher
.ignoreOutput()
.sink(receiveCompletion: { completion in
    print(".sink() received the completion", String(describing: completion))
    switch completion {
    case .finished: 
		    print("finished")
        break
    case .failure(let anError): 
        print("received error: ", anError)
        break
    }
}, receiveValue: { _ in 
    print(".sink() data received")
})

reduce/tryReduce

reduce按照闭包的规则把数据写到内存中,publisher发送数据完毕后,把收集到的所有数据一次性发出去,功能上scan类似,但是reduce会等待接收到所有数据后才处理数据

[1, 2, 3, 4, 5, 6, 7, 8]
    .publisher
    .reduce([], { preValue, newValue -> [Int] in
        newValue % 2 == 0 ? preValue + [newValue] : preValue
    })
    .sink(receiveCompletion: { completion in
        print("Finished")
        switch completion {
        case .finished:
            print("Finished")
            break
        case let .failure(error):
            print("Error:\(error.localizedDescription)")
            break
        }
    }, receiveValue: { someValue in
        print("someValue: \(someValue)")
    })

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1