iOS/iOS Swift 개발 일기

Combine 프로젝트 만들기 순서

Developer-Michelle 2023. 10. 22. 13:34

Combine 프로젝트 만들기 순서

 

1. Todos, Posts 모델 생성

1) Yarc(chrome-extension://ehafadccdcdedbhcbddihehiodgcddpl/index.html)에서 http://www.abc.com/123 이런식으로 url 넣고 GET 시도 -> response(응답값)을 복사.

 

2) QuickType(https://app.quicktype.io/) 에서 모델 생성

 

2. APIService 만들기

 

3. 위에서 만든 APISerivce를 ViewModel에서 구독 (sink)

Combine은 구독(sink)을 통해야 이벤트가 들어오게 된다.

 

import Foundation
import Combine

class ViewModel: ObservableObject {
    var subscriptions = Set<AnyCancellable>()
    
    func fetchTodos() {
        ApiService.fetchTodos()
            .sink { completion in
                switch completion {
                case .failure(let err):
                    print("ViewModel - fetchTodos: err: \(err)")
                case .finished:
                    print("ViewModel - fetchTodos: finished")
                }
            } receiveValue: { (todos: [Todo]) in
                print("ViewModel - fetchTodos/ todos: \(todos)")
            }.store(in: &subscriptions) //메모리에서 해제될 때 구독도 함께 취소된다 (RxSwift에서 disposeBag느낌)

    }
}

 

.store(in: &subscriptions) - 구독 취소 ( = RxSwift 의 disposeBag)


 

참고 > 정대리유튜브 (combine API 동시 호출) https://www.youtube.com/watch?v=73es1FDmm2g&t=1236s

내 깃허브 프로젝트명 > Combine_API_callAtTheSameTime


 

cf) enum 으로 만들어놓은면 가져올 때 따로 인스턴스 생성하지 않아도 됨