๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
IOS๐ŸŽ/Combine

[Combine] Cancellable์ด๋ž€

by Jouureee 2023. 4. 17.

element๋“ค์„ ๋ฐฉ์ถœํ•˜๋Š” ์ŠคํŠธ๋ฆผ์„ ๋‹ค ์‚ฌ์šฉํ–ˆ๋‹ค๋ฉด cancel() ํ•ด์ค˜์•ผ ์ž์›์ด dealloc ๋  ์ˆ˜ ์žˆ๋Š”๋ฐ์š”. ์ฆ‰ ์ด๋ฆ„ ๊ทธ๋Œ€๋กœ cancellation(์ทจ์†Œ)๋ฅผ ์œ„ํ•œ ํ”„๋กœํ† ์ฝœ์ž…๋‹ˆ๋‹ค. 

๋งŒ์•ฝ cancel()์„ ํ˜ธ์ถœํ•˜์ง€ ์•Š์œผ๋ฉด ์–ด๋–ป๊ฒŒ ๋ ๊นŒ์š” ?

viewController์˜ deinit()์ด ํ˜ธ์ถœ๋˜๊ณ  ๋‚˜๋„ ์ŠคํŠธ๋ฆผ์ด ์‚ด์•„์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ’์„ ๋ฐฉ์ถœํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. 

deinit {
    print("ViewController deinit")
}

let publisher = [1, 2, 3].publisher

publisher
    .map { $0 * 2 }
    .sink { value in
    print("\(value)")
}

//ViewController deinit
//2
//4
//6

 

์ŠคํŠธ๋ฆผ์ด ์‚ด์•„์žˆ๋‹ค๋ฉด Timer, network access, disk I/O์™€ ๊ฐ™์€ ์‚ฌ์ด๋“œ ์ดํŽ™ํŠธ๊ฐ€ ๋ฐœ์ƒํ• ์ˆ˜ ์žˆ๋‹ค๊ตฌ ํ•˜๋„ค์š”.

๊ทธ๋ ‡๋‹ค๋ฉด ์ด ๋ฌธ์ œ๋ฅผ ์–ด๋–ป๊ฒŒ ํ•ด๊ฒฐ ํ•  ์ˆ˜ ์žˆ์„๊นŒ์š” ?

๊ฐ’ ๋ฐœํ–‰ ํ›„ cancel()์„ ๋ช…์‹œ์ ์œผ๋กœ ํ˜ธ์ถœํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

var cancellable: Cancellable?

deinit {
    print("ViewController deinit")
    cancellable.cancel()
}

let publisher = [1, 2, 3].publisher

cancellable = publisher
    .map { $0 * 2 }
    .sink { value in
    print("\(value)")
}

//ViewController deinit
//2
//4
//6

 

AnyCancellable์€ ํด๋ž˜์Šค๋กœ Cancellable ํ”„๋กœํ† ์ฝœ์„ ์ฑ„ํƒํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. 

 

sink๋กœ ๊ฐ’์„ ๋ฐœํ–‰ํ• ๋•Œ ๋ฆฌํ„ด ํƒ€์ž…์ด AnyCancellable์ž…๋‹ˆ๋‹ค.

public func sink(receiveValue: @escaping ((Self.Output) -> Void)) -> AnyCancellable

 

์—ฌ๋Ÿฌ ์ŠคํŠธ๋ฆผ์ด ์žˆ์„๋•Œ cancellable๋“ค์„ ๋ฐ”๋กœ cancel() ํ•˜๋Š”๊ฒƒ์ด ์•„๋‹ˆ๋ผ ๋‚˜์ค‘์— dealloc์‹œ ํ•œ๋ฒˆ์— ํ•˜๊ณ  cancel() ํ•˜๊ณ  ์‹ถ์„๋•Œ

cancellable๋“ค์„ ๋‹ด์•„์ค„ ์ˆ˜ ์žˆ๋Š”๋ฐ์š”. store(in: Set<AnyCancellable>) ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

๋งˆ์น˜ RxSwift์˜ Disposbag()์ฒ˜๋Ÿผ cancellable์„ ๋งŒ๋“ค์–ด๋‘”๋’ค Cancellable ์ธ์Šคํ„ด์Šค๋“ค์„ ๋‹ด์•„์ค๋‹ˆ๋‹ค.

let cancellable = Set<AnyCancellabe>()

deinit {
    print("ViewController deinit")
}

let publisher = [1, 2, 3].publisher

cancellable = publisher
    .map { $0 * 2 }
    .sink { value in
    print("\(value)")
}.store(in: self.cancellable)

//ViewController deinit
//2
//4
//6

'IOS๐ŸŽ > Combine' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Combine] Scheduler๋ž€  (0) 2023.04.16
[Combine] ConnectablePublisher  (0) 2022.05.03
[Combine] Subject๋ž€ (AnyPublisher)  (0) 2022.04.17
[Combine] Combine, Publisher, Subscriber ์— ๋Œ€ํ•ด์„œ  (0) 2022.04.17

๋Œ“๊ธ€