๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

iOS/Reactive Programming

[Combine] ๊ฐœ์š” ๋ฐ Publisher ์™€ Subscriber์˜ ๊ฐœ๋…, Combine์˜ ์žฅ์ 

 

 

Combine์„ ์•Œ๊ธฐ ์ „์—, Functional Reactive Programming์ด ์–ด๋–ค ๋งฅ๋ฝ์—์„œ ๋‚˜์™”๋Š”์ง€ ์ดํ•ดํ•  ํ•„์š”๊ฐ€ ์žˆ๋‹ค.

 

ํ”„๋กœ๊ทธ๋ž˜๋ฐ ํŒจ๋Ÿฌ๋‹ค์ž„์€ Low Memory → Mass Production → Concurrency ์™€ ๊ฐ™์€ ๋งฅ๋ฝ์œผ๋กœ ๋ณ€ํ™”ํ•ด์™”๋Š”๋ฐ. ํ˜„์žฌ๋Š” Concurrency ๋‹จ๊ณ„๋กœ ์—ฌ๋Ÿฌ๊ฐœ์˜ ์Šค๋ ˆ๋“œ์—์„œ ์ž‘์—…์ด ์ด๋ฃจ์–ด์ง€๊ณ  ์žˆ๋Š” ํŒจ๋Ÿฌ๋‹ค์ž„์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค.

 

๊ทธ๋Ÿฌ๊ธฐ์— Side Effect๊ฐ€ ์žˆ์„ ์ˆ˜๋ฐ–์— ์—†์—ˆ๊ณ , ๊ทธ๋Ÿฌ๊ธฐ์— Pure Function์„ ์‚ฌ์šฉํ•˜๋Š” Functional ํŒจ๋Ÿฌ๋‹ค์ž„์ด ๋‚˜ํƒ€๋‚  ์ˆ˜ ๋ฐ–์— ์—†์—ˆ๋‹ค.

๊ทธ๋ฆฌ๊ณ  async ํ•œ ์ƒํ™ฉ์—์„œ asyncํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌํ•  ๊ฒƒ์ธ๊ฐ€? ์— ๋Œ€ํ•œ ๋Œ€๋‹ต์œผ๋กœ stream ์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ํ˜๋ ค๋ณด๋‚ด์ž๋Š” Reactive Programming์ด ๋‚˜์˜ค๊ฒŒ ๋˜์—ˆ๋‹ค.

Combine ์ด๋ž€?

๊ฐ„๋‹จํ•˜๊ฒŒ ๋งํ•ด์„œ, Combine์€ ์‹œ๊ฐ„์— ๋”ฐ๋ผ ๋ณ€ํ™”ํ•˜๋Š” ๊ฐ’์„ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•œ ์„ ์–ธ์  Swift API ์ด๋‹ค. ์ด ๊ฐ’๋“ค์€ ๋น„๋™๊ธฐ์ ์ธ ์—ฌ๋Ÿฌ ์ด๋ฒคํŠธ๋ฅผ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋‹ค. Combine ์—๋Š” Publisher์™€ Subscriber ๋ผ๋Š” ์ค‘์š”ํ•œ ๊ฐœ๋…์ด ์กด์žฌํ•œ๋‹ค.

 

Publisher, Subscriber

 

Publisher๋Š” ์ด๋ฒคํŠธ๋ฅผ ์ „๋‹ฌํ•˜๋Š” ์กด์žฌ์ด๋‹ค. Subscriber๋Š” Publisher๊ฐ€ ๋‚ด๋ณด๋‚ธ ์ด๋ฒคํŠธ๋ฅผ ์ˆ˜์‹ ํ•˜๋Š” ์กด์žฌ์ด๋‹ค.

  1. Publisher์˜ subscribe(_:) ๋ฉ”์„œ๋“œ์˜ ์ „๋‹ฌ์ธ์ž๋กœ Subscriber ์ธ์Šคํ„ด์Šค๋ฅผ ์ „๋‹ฌํ•˜์—ฌ ์ด ๋‘˜ ์‚ฌ์ด์˜ ์—ฐ๊ฒฐํ•œ๋‹ค.
  2. Publisher๋Š” Subscription์„ ์ „๋‹ฌํ•œ๋‹ค.
  3. Subscriber ๋Š” ์ „๋‹ฌ ๋ฐ›์€ Subscription์˜ request(_:) ๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด Publisher์˜ ๊ฐ’์„ ์ „๋‹ฌํ•˜๋ผ๊ณ  ์š”์ฒญํ•œ๋‹ค.
  4. Subscriber์˜ receive(_:) ๋ฉ”์„œ๋“œ๋Š” Publisher๋กœ๋ถ€ํ„ฐ ์ „๋‹ฌ๋ฐ›์€ ๊ฐ’์„ ์ฒ˜๋ฆฌํ•œ๋‹ค.
  5. ๋งŒ์•ฝ ๋” ์ด์ƒ Subscriber์—๊ฒŒ ์ „๋‹ฌํ•  ๊ฐ’์ด ์—†์œผ๋ฉด receive(completion:) ๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด completion, ํ˜น์€ ์˜ค๋ฅ˜๋ฅผ ์ „๋‹ฌ๋ฐ›๋Š”๋‹ค.

Combine ์˜ ์žฅ์ 

์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ ์ฝ”๋“œ๋ฅผ ์ค‘์•™ ์ง‘์ค‘ํ™”ํ•˜์—ฌ ์ฝ”๋“œ๋ฅผ ์ฝ๊ธฐ ์‰ฝ๊ณ  ์œ ์ง€๋ณด์ˆ˜ํ•˜๊ธฐ ์‰ฝ๊ฒŒ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค. ์ด๋Š” ์ค‘์ฒฉ ํด๋กœ์ €๋‚˜ ์ฝœ๋ฐฑ๊ฐ™์€ ๋ฒˆ๊ฑฐ๋กœ์šด ๊ธฐ๋ฒ•์„ ์ œ๊ฑฐํ•  ์ˆ˜ ์žˆ๋‹ค.