Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Collect, Collect with count and Map operator #1

Open
wants to merge 8 commits into
base: editions/3.0
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
226 changes: 193 additions & 33 deletions 03-transforming-operators/projects/Starter.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -3,36 +3,196 @@ import Combine

var subscriptions = Set<AnyCancellable>()

<#Add your code here#>

/// Copyright (c) 2021 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
// MARK: Collect
example(of: "Collect",
comment: "waits till the upstream publisher completes, and then collect all published values and send it in a single array to the downstram") {
["A", "B", "C", "D"].publisher
.collect()
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) })
.store(in: &subscriptions)
}

// MARK: Collect with Limit
example(of: "Collect(count)",
comment: "collects the values with the count number you pass, meaning that this operator will wait for the upstream publisher till it finishes and then send the values into the downstream into baches of the count you specifiy") {
["A", "B", "C", "D"].publisher
.collect(2)
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0)})
.store(in: &subscriptions)
}

// MARK: Map
example(of: "map") {
let numberFormatter = NumberFormatter()
numberFormatter.locale = .init(languageComponents: .init(language: .init(identifier: "ar")))
numberFormatter.numberStyle = .spellOut

[123, 4, 56].publisher
.map { numberFormatter.string(for: NSNumber(integerLiteral: $0)) ?? "" }
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) })
.store(in: &subscriptions)

// In this block, notice how:
// - The NumberFormatter can take different local / language and how the formatter got string from NSNumber Integer
// - How the ouptut become non-optional when adding the default value ?? ""
}

example(of: "Map key path") {
let publisher = PassthroughSubject<Coordinate, Never>()

publisher
.map(\.x, \.y)
.sink(receiveCompletion: { print($0) },
receiveValue: { x, y in
print(quadrantOf(x: x, y: y))
})
.store(in: &subscriptions)

publisher.send(.init(x: 2, y: 2))
publisher.send(.init(x: 2, y: -2))
publisher.send(.init(x: -2, y: 2))
publisher.send(.init(x: -2, y: -2))

let triplePublisher = PassthroughSubject<Tripple, Never>()

triplePublisher
.map(\.age, \.sex, \.name)
.sink(receiveCompletion: { print($0) },
receiveValue: { age, sex, name in
print(whatIsYourAge(name: name, age: age, sex: sex))
})
.store(in: &subscriptions)

triplePublisher.send(.init(age: 31, name: "Ahmed", sex: .male))
triplePublisher.send(.init(age: 30, name: "Rana", sex: .female))

}
example(of: "Try Map",
comment:"""
Notice in the `tryMap` operator
1. You have to use the try inside the tryMap operator.
2. The failure comes in thee completion branch.
3. You can build another example, something that can fail, and on fail you will see the failure when using tryMap
""") {
Just("Directory that doesn't exist")
.tryMap{ try
FileManager.default.contentsOfDirectory(atPath: $0)
}
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0)} )
.store(in: &subscriptions)
}


example(
of: "FlatMap",
comment: """
FlatMap operator flatten multiple upstream publishers into single downstream publisher that you can subscribe to it.
So you can have a publisher that emits a value and you want to flatMap the publisher it self into something else, i.e into another publisher.
So imagine you have a publisher of <String, Never> and you want to flatMap into <Int, Never>
or even <String, Never> => <String, Never> but doing different logic like the following example.
""") {
func decode(_ codes: [Int]) -> AnyPublisher<String, Never> {
Just(
codes
.compactMap{ code in
guard (32...128144).contains(code) else { return nil }
return String(UnicodeScalar(code) ?? " ")
}
.joined()
)
.eraseToAnyPublisher()
}

[128144, 32, 72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33, 32, 128144]
.publisher
.collect()
.flatMap(decode)
.sink(receiveCompletion: { print($0)},
receiveValue: { print($0)})
.store(in: &subscriptions)
}

example(
of: "Flat map 2",
comment:"""
With FlatMap Operator you can chain the upstream operators one after another, and return one publisher which will publish to the down stream.
Each upstream publisher input should be the output from the pervious publisher.
""") {

func oddOrEven(_ numbers: [Int]) -> AnyPublisher<[Bool], Never> {
Just (
numbers.compactMap { $0.isMultiple(of:2) }
).eraseToAnyPublisher()
}

func formatNumbers(_ numbers: [Bool]) -> AnyPublisher<String, Never> {
Just (
numbers
.map { return $0 == true ? "Even" : "Odd" }
.joined(separator: ", ")
).eraseToAnyPublisher()
}

func upperCase(_ string: String) -> AnyPublisher<String, Never> {
Just(
string.uppercased()
).eraseToAnyPublisher()
}

[1, 3, 18, 19, 500]
.publisher
.collect()
.flatMap(oddOrEven)
.flatMap(formatNumbers)
.flatMap(upperCase)
.sink(receiveValue: { print($0) } )
.store(in: &subscriptions)
}

example(of: "replaceNil") {
["A", nil, "B"]
.publisher
.eraseToAnyPublisher()
.replaceNil(with: "-")
.sink(receiveValue: { print($0) } )
.store(in: &subscriptions)
}

example(of: "Empty Publisher",
comment: """
There is new publisher type called Empty which is empty 🤷‍♂️, i.e Publisher that won't send anything
"""
) {
let empty = Empty<Int, Never>()
empty
.sink(receiveCompletion: { print($0) },
receiveValue: { $0 } )
.store(in: &subscriptions)
}

example(of: "Replace Empty") {
let empty = Empty<Int, Never>()
empty
.replaceEmpty(with: 5)
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) } )
.store(in: &subscriptions)

}

example(of: "Scan") {
var randomGenerator: Int { Int.random(in: -10...10) }
func random(_ number: Int) -> Int { randomGenerator }
let workingDaysValues = (0...25).map(random)
workingDaysValues
.publisher
.scan(50) { current, latest in
max(0, current + latest)
}
.sink { _ in }
.store(in: &subscriptions)
}
Original file line number Diff line number Diff line change
@@ -34,36 +34,66 @@ import Foundation
import Combine

public func example(of description: String,
comment: String = "",
action: () -> Void) {
print("\n——— Example of:", description, "———")
action()
print("\n——— Example of:", description, "———")
print("\t", description, comment)
action()
}

public struct Coordinate {
public let x: Int
public let y: Int

public init(x: Int, y: Int) {
self.x = x
self.y = y
}
public let x: Int
public let y: Int

public init(x: Int, y: Int) {
self.x = x
self.y = y
}
}


public struct Tripple {
public enum Sex {
case male, female
}

public let age: Int
public let name: String
public let sex: Sex

public init(age: Int, name: String, sex: Sex) {
self.age = age
self.name = name
self.sex = sex
}

}

public func whatIsYourAge(name:String, age: Int, sex: Tripple.Sex) -> String {
if case .male = sex {
let ageFormatter = NumberFormatter()
ageFormatter.locale = .init(identifier: "ar")
return ageFormatter.string(from: .init(value: age)) ?? ""
} else {
return "Non of your business! 💁‍♀️"
}
}

public func quadrantOf(x: Int, y: Int) -> String {
var quadrant = ""

switch (x, y) {
case (1..., 1...):
quadrant = "1"
case (..<0, 1...):
quadrant = "2"
case (..<0, ..<0):
quadrant = "3"
case (1..., ..<0):
quadrant = "4"
default:
quadrant = "boundary"
}

return quadrant
var quadrant = ""
switch (x, y) {
case (1..., 1...):
quadrant = "1"
case (..<0, 1...):
quadrant = "2"
case (..<0, ..<0):
quadrant = "3"
case (1..., ..<0):
quadrant = "4"
default:
quadrant = "boundary"
}
return quadrant
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
<LoggerValueHistoryTimelineItem
documentLocation = "file:///Users/ahmadatef/Development/Learning/Combine/03-transforming-operators/projects/Starter.playground#CharacterRangeLen=22&amp;CharacterRangeLoc=6185&amp;EndingColumnNumber=0&amp;EndingLineNumber=187&amp;StartingColumnNumber=0&amp;StartingLineNumber=186&amp;Timestamp=684948385.103197"
selectedRepresentationIndex = "0">
</LoggerValueHistoryTimelineItem>
<LoggerValueHistoryTimelineItem
documentLocation = "file:///Users/ahmadatef/Development/Learning/Combine/03-transforming-operators/projects/Starter.playground#CharacterRangeLen=24&amp;CharacterRangeLoc=6465&amp;EndingColumnNumber=0&amp;EndingLineNumber=194&amp;StartingColumnNumber=13&amp;StartingLineNumber=193&amp;Timestamp=684948385.103282"
selectedRepresentationIndex = "0">
</LoggerValueHistoryTimelineItem>
</TimelineItems>
</Timeline>
Original file line number Diff line number Diff line change
@@ -4,73 +4,85 @@ import Combine
var subscriptions = Set<AnyCancellable>()

example(of: "Create a phone number lookup") {
let contacts = [
"603-555-1234": "Florent",
"408-555-4321": "Marin",
"217-555-1212": "Scott",
"212-555-3434": "Shai"
]

func convert(phoneNumber: String) -> Int? {
if let number = Int(phoneNumber),
number < 10 {
return number
}

let keyMap: [String: Int] = [
"abc": 2, "def": 3, "ghi": 4,
"jkl": 5, "mno": 6, "pqrs": 7,
"tuv": 8, "wxyz": 9
let contacts = [
"603-555-1234": "Florent",
"408-555-4321": "Marin",
"217-555-1212": "Scott",
"212-555-3434": "Shai"
]

let converted = keyMap
.filter { $0.key.contains(phoneNumber.lowercased()) }
.map { $0.value }
.first

return converted
}

func format(digits: [Int]) -> String {
var phone = digits.map(String.init)
.joined()

phone.insert("-", at: phone.index(
phone.startIndex,
offsetBy: 3)
)

phone.insert("-", at: phone.index(
phone.startIndex,
offsetBy: 7)
)

return phone
}

func dial(phoneNumber: String) -> String {
guard let contact = contacts[phoneNumber] else {
return "Contact not found for \(phoneNumber)"

//4085554321

func convert(phoneNumber: String) -> Int? {
if let number = Int(phoneNumber),
number < 10 {
print("Found")
print(number)
return number
}

let keyMap: [String: Int] = [
"abc": 2, "def": 3, "ghi": 4,
"jkl": 5, "mno": 6, "pqrs": 7,
"tuv": 8, "wxyz": 9
]

let converted = keyMap
.filter { $0.key.contains(phoneNumber.lowercased()) }
.map { $0.value }
.first
print(converted)
return converted
}

func format(digits: [Int]) -> String {
var phone = digits.map(String.init)
.joined()

phone.insert("-", at: phone.index(
phone.startIndex,
offsetBy: 3)
)

phone.insert("-", at: phone.index(
phone.startIndex,
offsetBy: 7)
)

return phone
}

func dial(phoneNumber: String) -> String {
guard let contact = contacts[phoneNumber] else {
return "Contact not found for \(phoneNumber)"
}

return "Dialing \(contact) (\(phoneNumber))..."
}


let input = PassthroughSubject<String, Never>()

input
.map(convert)
.replaceNil(with: 0)
.collect(10)
.map(format)
.map(dial)
.sink(receiveValue: { print($0)})


// "0!1234567".forEach {
// input.send(String($0))
// }

"4085554321".forEach {
input.send(String($0))
}

"A1BJKLDGEH".forEach {
input.send("\($0)")
}

return "Dialing \(contact) (\(phoneNumber))..."
}

let input = PassthroughSubject<String, Never>()

<#Add your code here#>

"0!1234567".forEach {
input.send(String($0))
}

"4085554321".forEach {
input.send(String($0))
}

"A1BJKLDGEH".forEach {
input.send("\($0)")
}
}

/// Copyright (c) 2021 Razeware LLC
214 changes: 185 additions & 29 deletions 04-filtering-operators/projects/Starter.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -3,32 +3,188 @@ import Combine

var subscriptions = Set<AnyCancellable>()

<#Add your code here#>

/// Copyright (c) 2021 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
example(of: "Filter") {
(1...100)
.publisher
.filter({ $0.isMultiple(of: 3)})
.sink(receiveValue: { n in
print("\(n) is Multiple of 3!")
})
.store(in: &subscriptions)
}

example(of: "remove duplicates") {
["a", "b", "c", "a"]
.publisher
.removeDuplicates()
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)
"hey hey hey"
.components(separatedBy: " ")
.publisher
.removeDuplicates()
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)
}

example(of: "Drop and Prefix") {
let names = ["Ahmed Atef", "Ahmed Gamal","Mo Sharaf","Mo Gamal", "Ahmed Kamal"]
let prefixed = names.prefix { $0.hasPrefix("Ahmed") }

print(prefixed)

let dropped = names.drop { $0.hasPrefix("Ahmed") }
print(dropped)

let numbers = [2, 4, 6, 1, 8]
let prefixedNumbers = numbers.prefix { $0.isMultiple(of: 2) }
let droppedNumbers = numbers.drop { $0.isMultiple(of: 2) }
print(prefixedNumbers)
print(droppedNumbers)
}

example(of: "CompactMap") {
let strings = ["a", "1.24", "3", "def", "45", "0.23"].publisher
strings
.compactMap (Float.init)
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)
}

example(of: "ignoreOutput") {
// here we don't care about the values at all, we ignore the output.
// ignore everything, tell me when you finish.
let numbers = (1...10_000).publisher
numbers
.ignoreOutput()
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) })
.store(in: &subscriptions)
}

example(of: "first(where)") {
let numbers = (1...9).publisher
numbers
.print("numbers")
.first(where: { $0.isMultiple(of: 2) } )
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)
}
example(of: "last(where)") {
let numbers = (1...9).publisher
numbers
.print("📡")
.last(where: { $0.isMultiple(of: 2)})
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)
}

example(of: "last(where)",
detailedDescription: "the last(where) operator will not work, until the publisher complete the work") {
let subject = PassthroughSubject<Int, Never>()

subject
.print()
.first(where: { $0.isMultiple(of: 2)})
.last(where: { $0.isMultiple(of: 3) })
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)

subject.send(2)
subject.send(3)

subject.send(completion: .finished)
}

example(of: "dropFirst") {
let numbers = (1...10).publisher

numbers
.dropFirst(8)
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)
}

example(of: "dropWhile",
detailedDescription: """
dropWhile keeps dropping as the condition is true, the moment the condition becomes false then the publisher stops dropping and send through all the values...
"""
) {
let numbers = (1...10).publisher

numbers
.drop(while: { $0 % 5 != 0 } )
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)
}

example(of: "dropUntilOutputFrom") {
let isReady = PassthroughSubject<Void, Never>()
let taps = PassthroughSubject<Int, Never>()

taps
.drop(untilOutputFrom: isReady)
.sink(receiveValue: { print($0)})
.store(in: &subscriptions)

taps.send(1)
taps.send(3)
taps.send(4)

isReady.send()
taps.send(10)
taps.send(11)
}

example(of: "Prefix()") {
let numbers = (1...10).publisher

numbers
.prefix(2)
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0)})
.store(in: &subscriptions)
}

example(of: "Prefix(while)",
detailedDescription:
"""
prefix(while) start prefixing as long the condition is valid, the moment the condition becomes false, the prefixing operation
stops and the publisher completes
"""
) {
let numbers = (1...10).publisher

numbers
.prefix(while: { $0 < 5 })
.sink(receiveValue: { print($0)})
.store(in: &subscriptions)
}

example(of: "prefixUntilOutputFrom") {
let numbers = PassthroughSubject<Int, Never>()
let isReady = PassthroughSubject<Void, Never>()

numbers
.prefix(untilOutputFrom: isReady)
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)

numbers.send(1)
numbers.send(2)
numbers.send(3)

isReady.send()
numbers.send(4)
}

example(of: "challenge") {
let numbers = (1...100).publisher

numbers
.dropFirst(50)
.prefix(20)
.filter { $0 % 2 == 0 }
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)
}
Original file line number Diff line number Diff line change
@@ -29,7 +29,9 @@
import Foundation

public func example(of description: String,
detailedDescription: String? = nil,
action: () -> Void) {
print("\n——— Example of:", description, "———")
if let detailedDescription = detailedDescription { print(detailedDescription, "———") }
action()
}