๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐ŸŽ iOS/RxSwift

[iOS] RxSwift - Observables ์ƒ์„ฑ๊ณผ ๊ตฌ๋…, ์ƒ๋ช…์ฃผ๊ธฐ, operator

by Danna 2021. 7. 11.
728x90
728x90

๐Ÿ’ก ReacitveX - Observable 

  • ReactiveX ์—์„œ Observer ๋Š” Observable ์„ subscribe ํ•œ๋‹ค.
  • observer ๋Š” Observable ์ด ๋ฐฉ์ถœํ•˜๋Š” ์•„์ดํ…œ (๋‹จ์ผ ํ˜น์€ ์‹œํ€€์Šค)์— ์‘๋‹ตํ•œ๋‹ค. 
  • ์ด๋ฅผ ํ†ตํ•ด ๋™์‹œ์„ฑ(concurrency) ์—ฐ์‚ฐ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
  • Observable ์ด ๊ฐ์ฒด๋ฅผ ๋ฐฉ์ถœํ•  ๋•Œ๊นŒ์ง€ ๊ธฐ๋‹ค๋ฆด ํ•„์š” ์—†์ด, ๊ฐ์ฒด๊ฐ€ ๋ฐฉ์ถœ๋˜๋ฉด ๊ทธ ์‹œ์ ์„ ๊ฐ์‹œํ•˜๋Š” ๊ด€์ฐฐ์ž๋ฅผ observer ๋‚ด์— ๋‘๊ณ , ๊ทธ๋ฅผ ํ†ตํ•ด ์•Œ๋ฆผ์„ ๋ฐ›๋Š”๋‹ค.

 

โœ”๏ธŽ Observer ์ƒ์„ฑ & ๊ตฌ๋…

๋น„๋™๊ธฐ ๋ชจ๋ธ์—์„œ๋Š” ์•„๋ž˜์™€ ๊ฐ™์€ ํ๋ฆ„๋Œ€๋กœ ์ฝ”๋“œ๊ฐ€ ์‹คํ–‰๋œ๋‹ค.

 

  • async method ํ˜ธ์ถœ๋กœ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํ„ด๋ฐ›๊ณ , ํ•„์š”ํ•œ ๋™์ž‘์„ ์ฒ˜๋ฆฌํ•˜๋Š” method ๋ฅผ ์ •์˜ํ•œ๋‹ค. * Observer ์˜ ์ผ๋ถ€
  • Observable ๋กœ ๋น„๋™๊ธฐ ํ˜ธ์ถœ์„ ์ •์˜ํ•œ๋‹ค.
  • subscribe ๋ฅผ ํ†ตํ•ด observer ๋ฅผ Observable ๊ฐ์ฒด์— ์—ฐ๊ฒฐ์‹œํ‚จ๋‹ค.
  • onNext event ๋ฐœ์ƒ์‹œ ์ˆ˜ํ–‰ํ•  ์ฝ”๋“œ๋ฅผ ๊ตฌํ˜„ํ•œ๋‹ค.
๐ŸŒฑ Observable ์˜ ์ƒ๋ช…์ฃผ๊ธฐ
1. Create 
2. Subscribed 
3. Next (์ˆ˜ํ–‰)
- - - ๋ - - - 
4. Completed / Error 
5. Disposabled

 

โœ”๏ธŽ Observable ์„ ์ƒ์„ฑํ• ๋•Œ ์ด์šฉํ•˜๋Š” operator

  • Observable ์„ ์ƒ์„ฑํ•˜๋Š” ๊ธฐ๋ณธ operator
  • observer ์˜ onNext, onError, onCompleted ๋ฉ”์†Œ๋“œ๋ฅผ ์ ์ ˆํžˆ ํ˜ธ์ถœํ•ด ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.
  • Observable ์ƒ์„ฑ ํ›„, ์ „๋‹ฌํ•  ๋ฐ์ดํ„ฐ๋ฅผ onNext(data) ๋ฅผ ํ†ตํ•ด ์ „๋‹ฌํ•˜๊ณ , onCompleted() ๋ฅผ ํ†ตํ•ด ์ข…๋ฃŒํ•œ๋‹ค. 
  • Error ์ฒ˜๋ฆฌ๊ฐ€ ํ•„์š”ํ•  ๊ฒฝ์šฐ onError(error) ๋ฅผ ํ†ตํ•ด ์ „๋‹ฌํ•œ๋‹ค.
  • observer ์˜ onCompleted ํ˜น์€ onError ๋ฉ”์†Œ๋“œ๊ฐ€ ํ•œ๋ฒˆ์€ ํ˜ธ์ถœ๋˜์–ด์•ผ ํ•œ๋‹ค.

 

  • Observables.create ์™€ onNext(data) ๋ฅผ ํ•œ ๋ฒˆ์— ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” operator ์ด๋‹ค.
  • ๋ฐ์ดํ„ฐ๊ฐ€ ๋‹จ ํ•˜๋‚˜๋งŒ ์žˆ์„ ๊ฒฝ์šฐ Just ๋ฅผ ์ด์šฉํ•œ๋‹ค. 
  • ๋ฐ์ดํ„ฐ ํ•œ๊ฐœ๋ฅผ ์ „๋‹ฌํ•˜๋Š” ๊ฒƒ์ด์ง€๋งŒ, ๋ฐฐ์—ด ํ•˜๋‚˜๋ฅผ ์ „๋‹ฌํ•  ์ˆ˜๋„ ์žˆ๋‹ค. ์ด ๋•Œ์—๋Š” event ๊ฐ€ ํ•œ ๋ฒˆ ๋ฐœ์ƒํ•œ๋‹ค.

 

  • Observables.create ์™€ onNext(data) ๋ฅผ ํ•œ ๋ฒˆ์— ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” operator ์ด๋‹ค.
  • ๋ฐ์ดํ„ฐ๋ฅผ ์—ฌ๋Ÿฌ๊ฐœ, ๊ฐ ์ด๋ฒคํŠธ๋กœ ์ „๋‹ฌํ•  ๊ฒฝ์šฐ From ์„ ์ด์šฉํ•œ๋‹ค.
  • From์œผ๋กœ ์ „๋‹ฌ๋˜๋Š” ๋ฐ์ดํ„ฐ๋Š” array ํƒ€์ž…์œผ๋กœ, ๊ฐ ๋ฐฐ์—ด์˜ ์›์†Œ๊ฐ€ ๋ฐ์ดํ„ฐ๋กœ ์—ฌ๋Ÿฌ๋ฒˆ์˜ event ๋กœ ์ „๋‹ฌ๋œ๋‹ค.

โœ”๏ธŽ ๊ทธ ์™ธ์˜ Create ๊ด€๋ จ operator 

  • Empty :: ๋น„์–ด์žˆ๋Š” observable ์„ ์ „๋‹ฌํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์ด์šฉํ•œ๋‹ค.
  • Never :: ์ ˆ๋Œ€ observable ์„ ์ „๋‹ฌํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ ์ด์šฉํ•œ๋‹ค.
  • Throw :: observable ์„ ์ƒ์„ฑํ•˜๊ณ , error ๋ฅผ ์ „๋‹ฌํ•  ๊ฒฝ์šฐ ์ด์šฉํ•œ๋‹ค.

 

728x90
728x90