홍로그

Combine AnyCancellable 본문

iOS

Combine AnyCancellable

성홍민 2023. 6. 19. 16:19

📖 AnyCancellable이란?

Combine 프레임워크는 데이터 스트림을 비동기적으로 처리할 수 있는 도구입니다. 이 프레임워크는 Publisher, Subscriber, Operator, Cancellable 등의 주요 요소로 구성되어 있습니다. Combine에서 비동기 작업을 수행할 때는 주로 Publisher에서 생성한 이벤트를 Subscriber로 전달해 처리하게 됩니다. 이 과정에서, AnyCancellable은 매우 중요한 역할을 합니다. 그 이유는 구독 작업이 끝난 경우에 리소스를 해제하고 구독(subscription)을 취소하는 역할을 하기 때문입니다. 

 

객체가 생성되어 구독 과정이 시작되면, 실제로 구독 작업을 하는 동안 리소스가 사용됩니다. 이때 발생할 수 있는 문제점은 구독이 완료된 뒤에도 리소스가 해제되지 않아 메모리 누수가 발생할 수 있다는 점입니다. 따라서 구독 완료 후에 이러한 리소스를 제거하는 작업이 필요한데, 이때 AnyCancellable 객체가 필요한 것입니다.

 

AnyCancellable 객체는 구독이 완료되면 취소를 호출하여 구독 작업을 중지하고 해당 구독에 할당된 리소스를 해제합니다. 이렇게 함으로써 비동기 작업에서 발생할 수 있는 메모리 누수를 방지하는 데 매우 중요한 역할을 합니다.

예시코드

import Combine

class MyViewModel {
    private var cancellables = Set<AnyCancellable>()
    
    func fetchData() {
        URLSession.shared.dataTaskPublisher(for: URL(string: "https://api.example.com/items")!)
            .sink(receiveCompletion: { completion in
                // Handle completion here
            }, receiveValue: { [weak self] values in
                // Process and assign values to properties
            })
            .store(in: &cancellables) // Save the cancellable object
    }
}

위 코드에서 cancellables 속성은 AnyCancellable 객체의 집합을 저장합니다. store(in:) 메서드를 사용하여 생성된 구독을 자동으로 해제하는 disposal 시스템을 구축하게 됩니다. 이러한 구성으로 인해 구독이 더 이상 필요하지 않으면 자동으로 취소되며, 리소스를 알아서 해제하게 됩니다.

 

 

참고

https://developer.apple.com/documentation/combine/anycancellable

 

AnyCancellable | Apple Developer Documentation

A type-erasing cancellable object that executes a provided closure when canceled.

developer.apple.com

 

반응형

'iOS' 카테고리의 다른 글

Concurrency Programming  (0) 2023.06.22
DeepLink  (0) 2023.06.20
WWDC23 SwiftData  (0) 2023.06.14
SwiftUI @NameSpace  (0) 2023.06.13
SwiftUI ScrollView, ScrollViewReader, ScrollViewProxy  (0) 2023.06.12