avatar
Published on

ReactiveX) Subject

Author
  • avatar
    Name
    yceffort

subject๋Š” ์˜ต์ €๋ฒ„๋‚˜ observable์ฒ˜๋Ÿฌ ํ–‰๋™ํ•˜๋Š” ์ผ๋ถ€ ReactiveX๊ตฌํ˜„์ฒด์—์„œ๋งŒ ์‚ฌ์šฉ๊ฐ€๋Šฅํ•œ ์ผ์ข…์˜ ํ”„๋ก์‹œ๋‹ค. subject๋Š” ์˜ต์ €๋ฒ„์ด๊ธฐ ๋•Œ๋ฌธ์— ํ•˜๋‚˜์ด์ƒ์˜ observable์„ ๊ตฌ๋…ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๋™์‹œ์— observable ์ด๊ธฐ๋„ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ•ญ๋ชฉ์„ ํ•˜๋‚˜ํ•˜๋‚˜ ๊ฑฐ์น˜๋ฉด์„œ ๋‹ค์‹œ pushํ•˜๊ณ  ์ƒˆ๋กœ์šด ํ•ญ๋ชฉ์„ pushํ•  ์ˆ˜ ์žˆ๋‹ค.

์ด 4์ข…๋ฅ˜์˜ subject๊ฐ€ ์žˆ๋‹ค.

AsyncSubject

http://reactivex.io/documentation/operators../../../images/S.AsyncSubject.png

Observable์ด ๋งˆ์ง€๋ง‰์œผ๋กœ pushํ•œ ๊ฐ’๋งŒ push ํ•˜๊ณ , ์› Observable์˜ ๋™์ž‘์ด ๋‹ค ๋๋‚˜๋ฉด ๋™์ž‘ํ•œ๋‹ค. ์•„๋ฌด๊ฐ’๋„ push๋˜์ง€ ์•Š์œผ๋ฉด, ์ด subject ์—ญ์‹œ ๋ฐฐ์ถœํ•˜์ง€ ์•Š๋Š”๋‹ค. ๋˜ํ•œ ๋งจ ๋งˆ์ง€๋ง‰ ๊ฐ’ ๋ฐ”๋กœ ๋’ค์— ์˜ค๋Š” ์˜ต์ €๋ฒ„์—๋„ ๊ฐ’์„ ์ „๋‹ฌํ•˜๋Š”๋ฐ, ๋งŒ์•ฝ ์˜ค๋ฅ˜์— ์˜ํ•ด ์ข…๋ฅ˜๋  ๊ฒฝ์šฐ ์ด ์˜ค๋ฅ˜๋ฅผ ๊ทธ๋ƒฅ ์ „๋‹ฌํ•œ๋‹ค.

BehaviorSubject

http://reactivex.io/documentation/operators../../../images/S.BehaviorSubject.png ์˜ต์ €๋ฒ„๊ฐ€ BehaviorSubject๋ฅผ ๊ตฌ๋…ํ•˜๋ฉด, ์˜ต์ €๋ฒ„๋Š” Observable ์ด ๊ฐ€์žฅ ์ตœ๊ทผ์— ๋ฐœํ–‰ํ•œ ํ•ญ๋ชฉ (๋˜๋Š” ๊ฐ’์ด ์—†์„ ๊ฒฝ์šฐ ๋งจ์ฒ˜์Œ ๊ฐ’์ด๋‚˜ ๊ธฐ๋ณธ๊ฐ’) ์„ pushํ•˜๋ฉฐ, ์ดํ›„ Observable ์ด pushํ•œ ๊ฐ’์„ pushํ•œ๋‹ค.

PublishSubject

http://reactivex.io/documentation/operators../../../images/S.PublishSubject.png Subscribe ์ดํ›„์— pushํ•œ ํ•ญ๋ชฉ์— ๋Œ€ํ•ด์„œ ๋ชจ๋‘ Observable์—๊ฒŒ ๋ฐฐ์ถœํ•œ๋‹ค. ํ•˜์ง€๋งŒ ์ด ๋•Œ๋ฌธ์— subject๊ฐ€ ์ƒ์„ฑ๋˜๋Š” ์‹œ์ ๊ณผ ๊ตฌ๋…ํ•˜๋Š” ์‹œ์ ์‚ฌ์ด์— ๋นˆ ๊ณต๊ฐ„์ด ์ƒ๊ธด๋‹ค๋Š” ๋‹จ์ ์ด ์žˆ๋‹ค. ๋”ฐ๋ผ์„œ ๋ชจ๋“  pushํ•˜๋Š” ๋ชจ๋“  ํ•ญ๋ชฉ์„ ๋ฐ›๊ธฐ ์œ„ํ•ด์„œ๋Š” cold observable์„ ์ƒ์„ฑํ•˜๊ฑฐ๋‚˜, ์•„๋ž˜์˜ subject๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค.

RelaySubject

http://reactivex.io/documentation/operators../../../images/S.ReplaySubject.png PublishSubject ์™€ ๋‹ค๋ฅด๊ฒŒ, ๊ตฌ๋…ํ•œ ์‹œ์ ์— ์ƒ๊ด€์—†์ด Observable์ด pushํ•œ ๋ชจ๋“  ํ•ญ๋ชฉ์„ ๋ฐ›๋Š”๋‹ค. ๋‹ค๋งŒ ์žฌ์ƒ๋ฒ„ํผ์˜ ํฌ๊ธฐ๊ฐ€ ํŠน์ •์ด์ƒ์œผ๋กœ ์ฆ๊ฐ€ํ•  ๊ฒฝ์šฐ์—๋Š”, ์ฒ˜์Œ ๋ฐฐ์ถœํ›„ ์ง€์ •ํ•œ ์‹œ๊ฐ„์ด ๊ฒฝ๊ณผํ•˜๋ฉด ์˜ค๋ž˜๋œ ํ•ญ๋ชฉ์„ ์ œ๊ฑฐํ•œ๋‹ค. ๋˜ํ•œ onNext์‚ฌ์šฉ์„ ์ฃผ์˜ํ•ด์•ผํ•œ๋‹ค. (์ˆœ์„œ์˜ ๋ชจํ˜ธํ•จ์ด ์žˆ๊ธฐ ๋•Œ๋ฌธ)