Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 프로그래머스 자동커밋
- 프로그래머스 조건에 맞게 수열 변경하기 3
- 프로그래머스 문자열 정렬하기 (1)
- 스페인어
- 프로그래머스 문자열 붙여서 출력하기
- 프로그래머스 암호 해독
- 프로그래머스 n의 배수 고르기
- 프로그래머스 n번째 원소까지
- ruby설치
- 문자열 정렬하기 (1)
- 연산자
- 조건에 맞게 수열 변경하기 3
- 프로그래머스
- 프로그래머스 최댓값 만들기(2)
- swift
- 스파르타 코딩클럽 내일배움캠프
- array
- 배열 만들기1
- continue
- Break
- cocoapods 설치 오류
- 주사위 게임1
- 객체지향
- n번째 원소까지
- 프로그래머스 배열 만들기1
- 프로그래머스 주사위 게임1
- Error installing cocoapods
- 스파르타코딩캠프
- 문자열 붙여서 출력하기
- Til
Archives
- Today
- Total
dev._.note
[Swift-UI] Combine의 Cancellable (AnyCancellable) 사용 방법 본문
Cancellable
Combine 작업들을 취소할 수 있다는 의미를 가지고 있는 프로토콜
Combine에서는 이벤트 스트림을 action이라는 이름을 사용, action을 취소할 수 있는 프로토콜이 Cancellable이라는 의미
AnyCancellable
final public class AnyCancellable : Cancellable, Hashable
- .sink로 이벤트를 구독하면 리턴값으로 AnyCancellable이 얻어지는데 이 값을 가지고 cancel()하여 언제든지 구독을 취소시킬 수 있는 기능
final class MyModel {
@Published var number: Int
init(number: Int) {
self.number = number
}
}
let model = MyModel(number: 20)
let anyCancellable = model.$number
.sink { print($0) }
model.number = 10
model.number = 1
// 구독이 취소되어 더 이상 print($0)가 실행 x
anyCancellable.cancel()
model.number = 2
model.number = 3
/*
20
10
1
*/
RxSwift의 DisposeBag처럼 사용하기
- 특정 화면의 인스턴스가 해제되면 그 안에 있던 구독들도 같이 날아가게끔 하고 싶은 경우?
- store(in:)메소드를 사용하여 구현
https://developer.apple.com/documentation/combine/anycancellable/store(in:)-3hyxs
- Set<AnyCancellable>() 타입의 cancellables을 하나 선언해놓고, sink {} 밑에 .store(in:)을 선언하여 사용
var cancellables = Set<AnyCancellable>() // <-
let model = MyModel(number: 20)
let anyCancellable = model.$number
.sink { print($0) }
.store(in: &cancellables)
model.number = 10
model.number = 1
Apply 공식문서
'Dev > SWIFT UI' 카테고리의 다른 글
[Swift] 테이블뷰 스와이프 버튼(TableView swipe button) (0) | 2024.01.01 |
---|---|
[Swift-UI] UITableView 속성 (1) | 2023.12.21 |
[Swift-UI] UIView 컴포넌트 (1) | 2023.12.19 |
[Swift UI] Combine의 Operator - transfer (map, tryMap, flatMap, mapError, replaceNil, scan, tryScan, setFailureType) (0) | 2023.12.18 |
[Swift-UI] Combine이란? (0) | 2023.12.18 |