Combine

Jeom·2024년 6월 27일
post-thumbnail

Combine 이란?

Combine은 Apple의 Swift 프로그래밍 언어에 포함된 프레임워크로, 비동기적인 이벤트 스트림을 처리하고 조작하는 데 사용됩니다. 이는 함수형 프로그래밍과 반응형 프로그래밍 개념을 기반으로 하며, 데이터 스트림을 간단하게 조작하고 조합할 수 있는 도구를 제공합니다.

  1. Publisher(발행자):
    • 데이터 스트림을 생성하고, 이벤트를 방출하는 타입입니다.
    • 값을 방출할 수 있으며, 오류를 방출하거나 작업이 완료되었음을 알릴 수 있습니다.
  2. Subscriber(구독자):
    • Publisher에서 방출되는 이벤트를 받아 처리하는 타입입니다.
    • 값을 받아 처리하거나, 오류나 작업 완료 이벤트를 처리합니다.
  3. Operators(연산자):
    • Combine 프레임워크에는 데이터 스트림을 조작하고 변환하기 위한 다양한 연산자가 제공됩니다.
    • map, filter, flatMap 등의 연산자를 사용하여 데이터 스트림을 조작하고 새로운 형태로 변환할 수 있습니다.
  4. Cancellable(취소 가능한):
    • Combine에서는 구독을 취소할 수 있는 타입인 Cancellable이 제공됩니다.
    • 구독을 취소함으로써 더 이상 이벤트를 받지 않도록 설정할 수 있습니다.

swift 예시

import Foundation

class DataModel {
    var textValue: String = ""

    func updateText(to newValue: String) {
        textValue = newValue
        print("Value updated: \(textValue)")
    }
}

let dataModel = DataModel()

dataModel.updateText(to: "Hello, Swift!")
dataModel.updateText(to: "Another value")

/*
출력
Value changed to: Hello, Swift!
Value changed to: Another value
*/

// didset을 이용한 예시
class DataModel {
    var textValue: String = "" {
        didSet {
            print("Value updated: \(textValue)")
        }
    }
}

let dataModel = DataModel()

func changeText(to newValue: String) {
    dataModel.textValue = newValue
}

changeText(to: "Hello, Swift!")
changeText(to: "Another value")

/*
출력
Value changed to: Hello, Swift!
Value changed to: Another value
*/
profile
iOS 개발노트

0개의 댓글