엄한솔
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 1. [Hello, Combine!](https://www.kodeco.com/books/combine-asynchronous-programming-with-swift/v4.0/chapters/1-hello-combine) ## keyword - Combine - reactive app - chain ## 1.0 Combine이란? **Apple's own words**: >"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." >Combine은 앱의 이벤트를 처리하는 방법에 선언적 접근 방식을 제공한다. 콜백이나 컴플리션 핸들러를 구현하는 대신에 단일 처리 체인을 만든다. 체인의 각 부분은 이전 단계에서 받은 요소에 대해 고유한 작업을 수행하는 결합 연산자다. ## 1.1 Asynchronous Programming(비동기 프로그래밍) 단일 쓰레드의 언어에서 프로그램은 한줄씩 순차적으로 실행된다. ```code begin var name = "Tom" print(name) name += " Harding" print(name) end ``` 동기 코드는 이해하기 쉽고 데이터의 현재 상태를 항상 확인할 수 있다. 만약 다중 쓰레드 언어로 프로그램을 작성했다고 가정하자. ```code --- Thread 1 --- begin var name = "Tom" print(name) --- Thread 2 --- name = "Billy Bob" --- Thread 1 --- name += " Harding" print(name) end ``` Tom을 설정한 다음 Harding을 추가하지만, Thread2와 동시에 실행되므로 name이 **Billy Bob**일 수 있다. 서로 다른 코어에서 작동하기에 어느 부분이 먼저 수정될지는 알기 어렵다. 시스템 부하에 따라 다르며, 프로그램을 실행할 때마다 다른 결과가 표시될 수 있다. 비동기 코드를 실행하면 앱에서 변경 가능한 상태를 관리하는 것은 부하가 많이 걸리는 작업이다. ### Foundation and UIKit/AppKit Apple은 비동기 프로그래밍을 지속적으로 개선해 왔다. 비동기 코드를 생성하고 실행할 수 있도록 몇가지 메커니즘을 만들어 놨다. NSThread로 자체 스레드를 관리하는 것과 Async/Await을 사용하는 최신 동시성까지 사용할 수 있다. 일반적인 코드는 일부 작업을 비동기적으로 수행하고 모든 UI이벤트는 본질적으로 비동기적이기 때문에 앱 코드 전체가 어떤 순서로 실행될지 가정하는 것은 불가능하다. 하지만, 좋은 비동기 프로그램을 작성하는 것은 가능하다. ![image](https://hackmd.io/_uploads/rkF2ZzTgR.png) Combine은 비동기 코드를 설계하고 작성하기 위해 Swift 생태계에 공통의 high-level 언어를 도입한다. Apple은 Combine을 다른 프레임워크에서도 사용했기 때문에 Timer, NotificationCenter 및 Core Data와 같은 핵심 프레임워크와 통합하기 매우 쉽다. **SwiftUI에서도 Combine과 쉽게 통합할 수 있도록 설계되어 있다.** ## 1.2 Swift’s Modern Concurrency(Swift의 현대적 동시성) Swift 5.5에서 비동기 및 동시성 코드 개발을 위한 다양한 API가 도입됬다. 새로운 Threading-pool 모델 덕분에 비동기 작업을 안정하고 빠르게 일시 중단했다 시작할 수 있다. 새로운 동시성 구문은 비동기 작업 실행과 관련된 많은 문제를 해결하며, AsyncSequence및 AsyncStream과 같은 일부 companion API는 Combine과 같은 유사한 기능을 제공한다. Combine의 강점은 풍부한 operator 세트에 있다. 시간 경과에 따른 이벤트 처리를 위해 Combine을 사용하여 복잡하고 일반적인 시나리오를 쉽게 처리할 수 있다. Reactive operator는 네트워킹, 데이터처리, UI이벤트처리와 관련된 다양한 일반적인 문제를 직접 해결하므로 복잡한 애플리케이션의 경우 Combine을 사용하면 많은 이점이 있다. ## 1.3 Foundation of Combine Reactive 프로그래밍을 오랜전부터 사용되어 왔으며 최근 10년동안 눈에 띄게 성장했다. 2009년 Microsoft의 .NET용 반응형 확장(Rx.NET)이라는 라이브러리를 출시하면서 크게 등장했고, 2012년 Rx.NET을 오픈소스로 공개하며 다양한 언어에서 이 개념을 사용하기 시작했다. Apple의 경우 Rx표준을 구현하는 RxSwift, Interstellar, ReactiveSwift와 같은 타사의 프레임 워크가 있다. **Combine은 Rx와 다르지만 유사한 표준인 Reactive Streams을 구현한다. Reactive Stream과 Rx는 몇가지 주요 차이점이 있지만 대부분의 핵심 개념은 동일하다.** ## 1.4 Combine Basics Combine의 핵심 요소는 publisher, operator, subscriber이다. ### Pubilsher Pubilsher는 하나 이상의 관련 subscriber에게 시간이 지남의 다라 값을 내보낼 수 있는 유형이다. 수학계산, 네트워크, 사용자 이벤트 처리 등 거의 모든 것이 될 수 있는 Publisher의 내부 로직에 관계 없이 모든 publisher는 다음 세가지 유형의 이벤트를 여러개 보낼 수 있다. 타임라인에서 보이는 25초에 pubilsher와 subscriber의 stream이 종료된다. >1. publisher의 **generic Output** type >2. **successful completion** >3. publisher의 **failue**을 포함한 completion publishers는 0개 이상의 출력 값을 내보낼 수 있으며, 성공적으로 완료되거나 실패로 인해 완료되면 다른 이벤트를 내보내지 않는다. ![Image](https://hackmd.io/_uploads/HJYQjG6xA.png) <center>- Int값을 내보내는 publisher 타임라인 -</center> 위 타임라인에서 Stream은 25초에 성공적으로 완료했다. Pubilsher의 세가지 가능한 이벤트는 매우 보편적이어서 모든 종류의 동적 데이터를 나타낼 수 있다. Pubilsher의 가장 좋은 기능 중 하나는 오류 처리가 기본으로 제공된다는 점이다. 오류 처리를 원한다면 마지막에 선택적으로 추가할 수 있는 기능이 아니다. ![image](https://hackmd.io/_uploads/HJ9C3zaeR.png) 위 다이어그램에서 pubilsher의 protocol은 두가지로 나뉜다. >1. Publisher.Output: 출력값 유형 >2. Publisher.Failure: 실패할 경우 발생할 수 있는 오류 유형 특정 pubilsher를 구독하면 어떤 값을 기대할 수 있는지, 어떤 오류로인해 실패할 수 있는지 알 수 있다. ### Operators Operator는 동일하거나 새로운 퍼블리셔를 반환하는 퍼블리셔 프로토콜에 선언된 메서드다. 여러 연산자를 **차례로 호출**하여 효과적으로 연결할 수 있기 때문에 매우 유용하다. Operator라고 하는 메서드는 고도로 분리되어 있고 구성이 가능하기 떄문에 단일 Subscription 실행에 대해 매우 복잡한 로직을 구현하기 위해 **결합(Combined)** 할 수 있다. ![image](https://hackmd.io/_uploads/HJVrAVTxA.png) Operator는 항상 Upstream과 Downstream이라 하는 입력과 출력을 가지므로 데이터를 서로 전달하고 공유 상태의 변형을 피할 수 있다. Operator는 이전 오퍼레이터로부터 받은 데이터로 작업하고 그 결과를 체인의 다음 운영자에게 제공하는데 집중한다. 비동기적으로 실행되는 다른 어떤 코드도 작업 중인 데이터를 끼어들어 변경할 수 없다. ### Subscribers 모든 구독은 Subscriber와 함꼐 끝난다. Subscriber는 일반적으로 방출되는 출력 또는 완료 이벤트로 "무언가"를 수행한다. ![image](https://hackmd.io/_uploads/Hk3e1HaxR.png) 현재 Combine은 데이터스트림 작업을 간편하게 해주는 두가지 기본 Subscriber를 제공한다. > 1. Sink: 출력값과 완료를 수신할 코드에 클로저를 제공할 수 있다. 수신된 이벤트로 원하는 모든 작업을 수핼할 수 있다. > 2. assign: 사용자 지정 코드 없이 결과 출력을 데이터 모델의 일부 속성이나 UI컨트롤에 바인딩하여 키 경로를 통해 화면에 직접 데이터를 표시할 수 있다. 데이터에 대한 다른 요구사항이 있는 경우 Subscriber를 만드는 것도 매우 간단하다. ### Subscriptions ```text Note: Combine의 Subscription protocol, object, publisher, operator, subscriber를 설명하기 위해 subscription이란 용어를 사용해 전체 체인을 설명한다. ``` Subcription이 끝날 때, subscriber를 추가하면 체인의 시작 부분에서 publisher가 "active"된다. 수신할 subscriber가 없는 경우 publisher는 어떤 값도 내보내지 않는다. ![image](https://hackmd.io/_uploads/BJGqXBagR.png) Subcription이 코드가 성공적으로 커파일되고 사용자 정의 코드에 로직 문제가 없으면 완료된 것이다. 설계한대로 Subcription이는 사용자 제스처, 타이머가 울리는 등의 이벤트가 발생할 떄마다 비동기적으로 실행되어 Publisher중 하나를 꺠운다 Combine의 좋은점중 하나는 Cancellable이라는 프로토콜 덕분에 특별히 메모리 괄리를 할 필요가 없다. 예를들어 뷰 컨트롤러에서 프로퍼티에 저장하여 Subscription의 수명을 쉽게 바인딩할 수 있다. 이렇게하면 사용자가 뷰 스택에서 뷰컨트롤러를 해제할 떄마다 해당 속성이 초기화 되고 구독도 취소된다. ## 1.5 App Architecture Combine은 앱 구조에 영향을 미치는 프레임워크가 아니다. Combine은 비동기 데이터 이벤트와 통함 커뮤니케이션 constract를 다루며, 프로젝트의 책임을 분리하는 방법은 변경되지 않는다. MVC, MVVM 에서 사용할 수 있고 SwiftUI 앱에도 결합할 수 있다. 데이터모델을 변환하거나 네트워킹 계층을 조정하거나 기존 기능을 그대로 유지하면서 앱에 추가하는 새 코드에서만 결합을 사용하는 것으로 시작할 수 있다. 하지만 SwiftUI와 Combine은 실제로 함께 작동하도록 설계되었다. 뷰컨트롤러는 Combine/SwiftUI팀에 대항할 수 없다. 반응형 프로그래밍을 사용하여 데이터를 뷰에 바인딩하는 경우 뷰를 제어하기 위해 틀별한 컨트롤러가 필요하지 않다. ![image](https://hackmd.io/_uploads/SkPpABpxC.png) ## 1.6 Book Projects ## 1.7 Key Points - Combine is a declarative, reactive framework for processing asynchronous events over time. >Combine은 시간이 지남에 따라 비동기 이벤트를 처리하기 위한 선언적, 반응형 프레임워크입니다. - It aims to solve existing problems, like unifying tools for asynchronous programming, dealing with mutable state and making error handling a starting team player. >비동기 프로그래밍을 위한 도구 통합, 가변 상태 처리, 오류 처리의 팀 플레이어화 등 기존의 문제를 해결하는 것을 목표로 합니다. - Combine revolves around three main types: publishers to emit events over time, operators to asynchronously process and manipulate upstream events and subscribers to consume the results and do something useful with them. >Combine은 세 가지 주요 유형, 즉 시간에 따라 이벤트를 방출하는 퍼블리셔, 업스트림 이벤트를 비동기적으로 처리하고 조작하는 운영자, 결과를 소비하고 유용한 작업을 수행하는 구독자를 중심으로 돌아갑니다. ## 1.8 Where to Go From Here?

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully