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 으로 만들어놓은면 가져올 때 따로 인스턴스 생성하지 않아도 됨
'iOS > iOS Swift 개발 일기' 카테고리의 다른 글
토스트 메시지 띄우고 화면 전환 동시에 되는 경우 (0) | 2023.09.04 |
---|---|
Deep Link -target iOS 13 이하 대응 (0) | 2023.04.15 |
카카오맵 api 라이브러리 설치 (0) | 2023.04.09 |
아키텍쳐 MVC, MVVM (0) | 2023.02.18 |
ios swift) 테두리 둥글게 - clipsToBounds (0) | 2022.11.19 |