[swift] Combine 프레임워크와 데이터의 비동기적 처리

Combine은 Apple의 프레임워크로, 비동기적 이벤트 처리와 데이터 스트림 관리에 사용됩니다. SwiftUI와 함께 사용되며, 네트워크 호출 결과 처리, 사용자 입력 처리, 그 외 다양한 비동기 작업을 보다 간결하게 처리할 수 있습니다.

이번에는 Combine 프레임워크를 사용하여 데이터의 비동기적 처리를 살펴보겠습니다.

Combine 개요

Combine 프레임워크는 선언형 패러다임을 기반으로 하고 있으며, 주로 Publisher와 Subscriber로 이루어져 있습니다. Publisher는 데이터 스트림을 생성하고, Subscriber는 해당 데이터를 소비합니다.

비동기적 네트워크 호출 예제

아래 예제 코드를 통해, Combine을 사용하여 비동기적으로 네트워크 호출을 처리하는 방법을 알아봅시다.

import Combine
import Foundation

// 1. 데이터 모델 정의
struct Post: Decodable {
    let userId: Int
    let id: Int
    let title: String
    let body: String
}

// 2. API 호출을 위한 함수 정의
func fetchPosts() -> AnyPublisher<[Post], Error> {
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
    return URLSession.shared.dataTaskPublisher(for: url)
        .map { $0.data }
        .decode(type: [Post].self, decoder: JSONDecoder())
        .eraseToAnyPublisher()
}

// 3. Combine을 사용한 네트워크 호출
let cancellable = fetchPosts()
    .sink(receiveCompletion: { completion in
        if case .failure(let error) = completion {
            // 에러 처리
            print("Error: \(error.localizedDescription)")
        }
    }, receiveValue: { posts in
        // 성공 시 데이터 처리
        print("Fetched posts: \(posts)")
    })

위 예제에서, fetchPosts() 함수는 URLSession을 이용하여 API를 호출하고, 데이터를 받아오는 비동기 작업을 Combine을 통해 처리합니다.

결론

Combine 프레임워크를 사용하면 네트워크 호출, 사용자 입력, 데이터 변환 등과 같은 다양한 비동기적 작업을 보다 간결하고 효율적으로 처리할 수 있습니다. 이는 SwiftUI와의 호환성이 높아 모던 iOS 앱 개발에 매우 유용하게 사용될 수 있습니다.

더 많은 Combine에 관한 내용은 Apple의 공식 문서를 참고하시기 바랍니다.