Skip to content

Instantly share code, notes, and snippets.

@HashNuke
Last active August 31, 2022 11:24
Show Gist options
  • Select an option

  • Save HashNuke/248a92f0be4441e02846cdd532192f40 to your computer and use it in GitHub Desktop.

Select an option

Save HashNuke/248a92f0be4441e02846cdd532192f40 to your computer and use it in GitHub Desktop.

Revisions

  1. HashNuke revised this gist Jun 30, 2020. 1 changed file with 2 additions and 10 deletions.
    12 changes: 2 additions & 10 deletions combine-flatMap-reduce-tryout.swift
    Original file line number Diff line number Diff line change
    @@ -9,10 +9,10 @@ let cancellable = publisher
    .flatMap { Just($0).setFailureType(to: Error.self) }
    .handleEvents(
    receiveOutput: {(n:Int) in
    // sends one more event if n < 5
    // mimics pagination
    if n < 5 {
    publisher.send(n + 1)
    } else {
    publisher.send(completion: .finished)
    }
    }
    )
    @@ -36,11 +36,3 @@ let cancellable = publisher
    )

    publisher.send(1)


    // -- OUTPUT --
    // Collecting items in reduce: 0
    // Collecting items in reduce: 1
    // Collecting items in reduce: 2
    // Collecting items in reduce: 3
    // Collecting items in reduce: 4
  2. HashNuke revised this gist Jun 30, 2020. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions combine-flatMap-reduce-tryout.swift
    Original file line number Diff line number Diff line change
    @@ -9,6 +9,8 @@ let cancellable = publisher
    .flatMap { Just($0).setFailureType(to: Error.self) }
    .handleEvents(
    receiveOutput: {(n:Int) in
    // sends one more event if n < 5
    // mimics pagination
    if n < 5 {
    publisher.send(n + 1)
    }
  3. HashNuke created this gist Jun 30, 2020.
    44 changes: 44 additions & 0 deletions combine-flatMap-reduce-tryout.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    import Combine
    import Foundation
    import PlaygroundSupport
    PlaygroundPage.current.needsIndefiniteExecution = true

    var publisher = PassthroughSubject<Int, Error>()

    let cancellable = publisher
    .flatMap { Just($0).setFailureType(to: Error.self) }
    .handleEvents(
    receiveOutput: {(n:Int) in
    if n < 5 {
    publisher.send(n + 1)
    }
    }
    )
    .reduce([Int](), {allItems, n in
    print("Collecting items in reduce:", allItems.count)
    return allItems + [n]
    })
    .sink(
    receiveCompletion: {completion in
    switch completion {
    case .finished:
    print("Completed")
    break
    case .failure(let error):
    print(error.localizedDescription)
    }
    },
    receiveValue: { values in
    print("All values:", values)
    }
    )

    publisher.send(1)


    // -- OUTPUT --
    // Collecting items in reduce: 0
    // Collecting items in reduce: 1
    // Collecting items in reduce: 2
    // Collecting items in reduce: 3
    // Collecting items in reduce: 4