Last active
May 4, 2020 18:06
-
-
Save masliukivskyi/7c49dd9dce36c7a053ff07e231535f4f to your computer and use it in GitHub Desktop.
Combine example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// mapping | |
_ = [1,2,3,5,8,12] | |
.publisher | |
.map { $0%2 } | |
.sink(receiveValue: { (value) in | |
print(value) | |
}) | |
Output: 1 0 1 1 0 0 | |
// filtering | |
_ = [1,2,3,5,8,12] | |
.publisher | |
.filter { $0%2 == 0 } | |
.sink(receiveValue: { (value) in | |
print(value) | |
}) | |
Output: 2 8 12 | |
// min | |
_ = [1,2,3,5,8,12] | |
.publisher | |
.min() | |
.sink(receiveValue: { (value) in | |
print(value) | |
}) | |
Output: 1 | |
// reduce | |
_ = [1,2,3,5,8,12].publisher.reduce("", { (text, value) -> String in | |
if value % 2 == 0 { | |
return text + " Even" | |
} else { | |
return text + " Odd" | |
} | |
}).sink(receiveValue: { (value) in | |
print(value) | |
}) | |
Output: Odd Even Odd Odd Even Even | |
// decode | |
struct DummyDecodable: Decodable { | |
let userName: String | |
let userId: Int | |
} | |
let dataProvider = PassthroughSubject<Data, Never>() | |
_ = dataProvider | |
.decode(type: DummyDecodable.self, decoder: JSONDecoder()) | |
.sink(receiveCompletion: { completion in | |
print(completion) | |
}, receiveValue: { response in | |
print(response.userName) | |
}) | |
dataProvider.send(Data("{\"userName\":\"Alex\",\"userId\":1}".utf8)) | |
Output: Alex |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment