Combine을 통한 데이터 바인딩
ViewModel에서 @Published와 sink, assign을 활용해 뷰에 데이터를 구독하고 실시간으로 UI에 반영할 수 있다.
@Published, sink, assign의 사용 방법에 대해 알아보자.
1. @Published:
- ObservableObject 프로토콜을 채택한 클래스에서 사용.
- 값이 변경될 때마다 뷰(구독자)에게 알림을 보내 UI를 자동으로 업데이트.
@Published var temperature: Double = 0.0
2. sink(receiveCompletion:receiveValue:):
- 퍼블리셔에서 값을 받을 때 사용하는 구독 메서드.
- 네트워크 요청이 성공하거나 실패할 때 동작을 정의.
WeatherAPIManager.shared.fetchCurrentWeather(lat: lat, lon: lon)
.sink(receiveCompletion: { completion in
// 완료 시 처리
}, receiveValue: { weatherData in
// 데이터 수신 시 처리
})
.store(in: &cancellables)
3. assign(to:on:):
- 퍼블리셔의 값을 특정 객체의 프로퍼티에 직접 할당.
WeatherAPIManager.shared.fetchCurrentWeather(lat: lat, lon: lon)
.map { $0.main.temp }
.assign(to: \.temperature, on: self)
.store(in: &cancellables)
'Devlog👩🏻💻 > iOS' 카테고리의 다른 글
[iOS] CoreLocation 사용하기 (0) | 2025.02.14 |
---|---|
[iOS] Alamofire + Combine으로 API 요청하기 (0) | 2025.02.12 |
[iOS] CollectionView 페이징 (Pagination), LoadMore (0) | 2024.06.29 |
[iOS] 스냅킷 updateLayoutConstraints 크래시 (equalToSuperview) (2) | 2024.06.19 |
[Error/Xcode] 시뮬레이터 SearchBar & TextField 키보드 오류 (4) | 2024.05.07 |