[ios] Combine 프레임워크의 실제 적용 사례

Combine은 Swift에서 비동기 작업을 처리하고 이를 간결하게 관리하기 위한 프레임워크입니다. 이번 포스트에서는 Combine의 실제적인 적용 사례를 살펴봅니다.

Combine이란

Combine은 Swift에서 비동기 이벤트 스트림을 다루기 위한 프레임워크로, Swift의 함수형 프로그래밍과 비동기 프로그래밍을 결합하는 목적으로 만들어졌습니다. Combine을 사용하면 비동기 코드를 쉽게 작성하고 관리할 수 있으며, RxSwift나 Kotlin의 Coroutine과 유사한 기능을 제공합니다.

실제 적용 사례

네트워크 요청 및 응답 처리

Combine을 사용하여 네트워크 요청을 하고 응답을 처리하는 예제 코드를 살펴보겠습니다.

import Combine
import Foundation

struct Post: Codable {
    let userId: Int
    let id: Int
    let title: String
    let body: String
}

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()
}

fetchPosts()
    .sink(receiveCompletion: { completion in
        // handle completion (success or failure)
    }, receiveValue: { posts in
        // handle received posts
    })

사용자 입력 이벤트 핸들링

사용자의 입력에 따라 비동기 처리를 하고 그 결과를 반영하는 예제 코드를 살펴보겠습니다.

import Combine
import UIKit

class SearchViewController: UIViewController {
    private let searchTextField = UITextField()
    
    private var searchCancellable: AnyCancellable?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        searchCancellable = NotificationCenter.default.publisher(for: UITextField.textDidChangeNotification, object: searchTextField)
            .map { ($0.object as! UITextField).text }
            .filter { text in
                text.count >= 3
            }
            .debounce(for: .milliseconds(500), scheduler: RunLoop.main)
            .removeDuplicates()
            .sink { text in
                // handle search request with text
            }
    }
}

요약

Combine 프레임워크는 Swift에서 비동기 코드를 다루는데 매우 유용한 도구입니다. 네트워크 요청 및 응답 처리, 사용자 입력 핸들링 등의 다양한 상황에서 Combine을 활용하여 코드를 더 간결하게 작성하고 관리할 수 있습니다.

이렇게 실제 코드 예제를 통해 Combine이 어떻게 활용되고 있는지 살펴보았습니다. Combine을 사용하여 비동기 작업을 효과적으로 다룰 수 있다는 것을 알 수 있었습니다.

Combine 프레임워크 공식 문서