1. Hello Combine

    The Combine framework provides a declarative approach for how your app processes events. Rather than potentially implementing multiple delegate callbacks or completion handler closures, you can create a single processing chain for a given event source. Each part of the chain is a Combine operator that performs a distinct action on the elements received from the previous step.

    → 지정된 이벤트에 대한 단일 처리 체인을 만들 수 있다! 라는 것이 포인트인 것 같음

    UIKit / AppKit 에서 발견할 수 있는 비동기 프로그래밍을 위한 도구

    NotificationCenter / Delegate pattern / GCD & Operation / Closure

  2. Combine basics

3가지 핵심 키워드 : Publishers, Operators, Subscribers


  1. Publishers & Subscirbers

    Publisher는 관심있는 이벤트를 publish 하거나 emit 할 수 있다.

    publisher를 subscribing하는 개념은 NotificationCenter가 특정 notification을 subscribing 하는 개념과 유사하다.

    NotificationCenter를 통해 특정 이벤트에 관심을 표시하고, 새 이벤트가 발생할 때마다 비동기식으로 알림을 받을 수 있다.

    NotifcationCenter는 publisher(for:object:)라는 이름의 메소드를 갖고 있다.

    Untitled

    Untitled

    기존 NotifcationCenter를 이용하여 비동기처리가 가능한데 publisher가 갖는 이점은 무엇일까? → publisher는 이전에 사용했던 비동기API를 새로운 대안과 연결해주는 다리 역할을 하게 된다

    Pulbisher는 두가지 이벤트를 내보낸다. values, completion event.

    Publisher는 values 값을 아예 보내지 않을 수도 혹은 1개 이상의 값을 내보낼 수도 있다. 하지만 completion event는 딱 한개만 내보낸다. completion event의 값은 정상값 혹은 에러값이다.

    Publisher가 completion event를 내보낼때 publisher의 역할은 끝나고 더이상 이벤트를 내보내지 않게 된다.

    Sink 오퍼레이터의 특징

    1. Publisher가 제공해주는만큼 값을 전달받을 수 있다.

    2. 2가지 클로저를 제공해준다 → completion event, receive value

    Just

    Untitled

    Just는 Publisher 이다. 이벤트 결과를 각 Subscriber 에게 한번씩 전달하면 완료 상태가 된다.


    Subscribing with assign(to:on:)

    assing(to:on:) → KVO에 맞는 개체를 할당해준다.

    Untitled

    UIKit의 경우 labels, text view, checkbox 등에 values를 전달하는 경우가 많은데 이때 유용하게 사용할 수 있다.

    Republishing with assign(to:)

    Untitled

    Publisher로 부터 받은 받은 값을 다시 Publish 하는 것이 republish.

    @Published 속성을 사용하여 표현할 수 있음.

    Untitled

    assign(to:on:) 대신 assign(to:) 을 사용하면 강한참조 문제를 해결할 수 있다.


    Hello Cancellable

    subscriber 가 작업을 마치고 더 이상 publisher로 부터 값을 받고 싶지 않다면 subscription을 취소하여 리소스를 확보하고 네트워크 호출과 같은 활동이 일어나지 않도록 하는 것이 좋다.

    subscription에 대해 명시적으로 cancel() 메서드를 호출하지 않으면 publisher가 완료될 때까지

    또는 저장된 subscription 이 deintialize 될 때까지 계속된다. 내가 직접 subscription을 취소할때 사라진다는 의미.


    Understanding what’s going on

    Untitled


    Creating a custom subscriber

    Untitled


Hello Future

Just 를 사용하여 subscriber에게 단일 값을 보내고 완료하는 publisher를 만들 수 있는 것과 마찬가지로

Future 를 사용하여 단일 결과를 비동기적으로 생성하여 완료할 수 있습니다.

Untitled

Promise 타입은 클로저로서 Result 받거나 Error 를 받을 수 있습니다.

Result 는 Future 에 의해 publish 된 단일 값을 포함하고 있습니다.

Future는 greedy 하다! 생성되는 그 즉시 바로 실행된다.

일반적인 publisher 들은 subscriber를 필요로 한다 ← lazy 이기 때문에


Hello Subject

example(of: "PassthroughSubject") {
  // 1
  enum MyError: Error {
    case test
  }

  // 2
  final class StringSubscriber: Subscriber {
    typealias Input = String
    typealias Failure = MyError

    func receive(subscription: Subscription) {
      subscription.request(.max(2))
    }

    func receive(_ input: String) -> Subscribers.Demand {
      print("Received value", input)
      // 3
      return input == "World" ? .max(1) : .none
    }

    func receive(completion: Subscribers.Completion<MyError>) {
      print("Received completion", completion)
    }
  }

  // 4
  let subscriber = StringSubscriber()
}