CurrentValueSubject

์ œ๋„ค๋ฆญ ํด๋ž˜์Šค | ํ•˜๋‚˜์˜ ๊ฐ’์„ ๊ฐ์‹ธ๊ณ  ๊ฐ’์ด ๋ณ€ํ™”ํ•  ๋•Œ๋งˆ๋‹ค ์ƒˆ๋กœ์šด ์š”์†Œ๋ฅผ ๋‚ด๋Š” Subject

PassthroughSubject์™€๋Š” ๋‹ค๋ฅด๊ฒŒ ์ดˆ๊ธฐ๊ฐ’์„ ๊ฐ€์ง€๋ฉฐ, ๊ฐ€์žฅ ์ตœ๊ทผ์— ๋ฐœํ–‰๋œ ์š”์†Œ์— ๋Œ€ํ•œ ๋ฒ„ํผ๋ฅผ ์œ ์ง€ํ•œ๋‹ค.

๋‘ ๊ฐœ์˜ ์ œ๋„ค๋ฆญ ํƒ€์ž…์„ ๊ฐ€์ง„๋‹ค. ํ•˜๋‚˜๋Š” ๊ฐ’์˜ ํƒ€์ž…์„ ๋‚˜ํƒ€๋‚ด๋ฉฐ, ๋‹ค๋ฅธ ํ•˜๋‚˜๋Š” ์—๋Ÿฌ์˜ ํƒ€์ž…์„ ๋‚˜ํƒ€๋‚ธ๋‹ค. ์—๋Ÿฌ์˜ ํƒ€์ž…์€ Error ํ”„๋กœํ† ์ฝœ์„ ์ฑ„ํƒํ•ด์•ผ ํ•œ๋‹ค.

์ด๋‹ˆ์…œ๋ผ์ด์ €์— ๋ฐœํ–‰ํ•  ์ดˆ๊ธฐ๊ฐ’์„ ๋„˜๊ฒจ์ฃผ์–ด ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

value ํ”„๋กœํผํ‹ฐ๋ฅผ ํ†ตํ•˜์—ฌ ํ•ด๋‹น Subject๊ฐ€ ๊ฐ์‹ผ ๊ฐ’์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค.

let subject = CurrentValueSubject<Void, Never>(Void())
subject
  .sink(receiveCompletion: { completion in
    switch completion {
    case .failure:
      print("Combine CurrentValueSubject Error")
    case .finished:
      print("Combine CurrentValueSubject Finish")
    }
  }, receiveValue: {
    print("Combine CurrentValueSubject")
  })
  .store(in: &cancellables)

subject.send(Void())

// Combine CurrentValueSubject
// Combine CurrentValueSubject

์ดˆ๊ธฐ๊ฐ’์„ ์„ค์ •ํ•˜์˜€์œผ๋ฏ€๋กœ subject๋ฅผ ๊ตฌ๋…ํ•œ ์ˆœ๊ฐ„์— ๊ฐ’์„ ๋ฐ›์€ ๊ฒƒ์— ๋Œ€ํ•œ ํด๋กœ์ €๊ฐ€ ์‹คํ–‰๋œ๋‹ค.

์ดํ›„ subject.send(Void())๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ Subject์— ๊ฐ’์„ ์ „๋‹ฌํ•˜์˜€์œผ๋ฏ€๋กœ ๊ฐ’์„ ๋ฐ›์€ ๊ฒƒ์— ๋Œ€ํ•œ ํด๋กœ์ €๊ฐ€ ํ•œ ๋ฒˆ ๋” ์‹คํ–‰๋œ๋‹ค.

RxSwift

BehaviorSubject๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

let subject = BehaviorSubject(value: Void())
subject
  .subscribe(onNext: {
    print("RxSwift CurrentValueSubject")
  }, onError: { _ in
    print("RxSwift CurrentValueSubject Error")
  }, onCompleted: {
    print("RxSwift CurrentValueSubject Finish")
  })
  .disposed(by: disposeBag)

subject.onNext(Void())

// RxSwift CurrentValueSubject
// RxSwift CurrentValueSubject

onNext(_:) ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ Subject์— ๊ฐ’์„ ์ „๋‹ฌํ•œ๋‹ค.

ReactiveSwift

MutableProperty๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  producer ํ”„๋กœํผํ‹ฐ๋ฅผ ํ†ตํ•ด SignalProducer๋ฅผ ๋งŒ๋“ค์–ด ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

let property = MutableProperty(Void())
property.producer
  .start { event in
    switch event {
    case .value:
      print("ReactiveSwift CurrentValueSubject")
    case .failed:
      print("ReactiveSwift CurrentValueSubject Error")
    case .completed:
      print("ReactiveSwift CurrentValueSubject Finish")
    default:
      break
    }
  }

property.value = Void()

// ReactiveSwift CurrentValueSubject
// ReactiveSwift CurrentValueSubject
// ReactiveSwift CurrentValueSubject Finish

value ํ”„๋กœํผํ‹ฐ์— ๊ฐ’์„ ํ• ๋‹นํ•˜์—ฌ Property์— ๊ฐ’์„ ์ „๋‹ฌํ•œ๋‹ค.

MutableProperty๋กœ๋ถ€ํ„ฐ signal ํ”„๋กœํผํ‹ฐ๋ฅผ ํ†ตํ•ด Signal์„ ๋งŒ๋“ค์–ด ์‚ฌ์šฉํ•œ๋‹ค๋ฉด, MutableProperty์˜ ์ดˆ๊ธฐ๊ฐ’์ด ํ๋ฅด๊ฒŒ ๋˜์ง€ ์•Š์œผ๋ฏ€๋กœ CurrentValueSubject์˜ ๋™์ž‘์„ ๊ตฌํ˜„ํ•  ์ˆ˜ ์—†๋‹ค.

์Šค์ฝ”ํ”„๋ฅผ ๋ฒ—์–ด๋‚  ๋•Œ property๊ฐ€ ํ•ด์ œ๋˜์–ด SignalProducer๋„ ์ข…๋ฃŒํ•˜๋Š” ๋ชจ์Šต์„ ๋ณด์—ฌ์ค€๋‹ค.

์ฐธ๊ณ 

ReactiveX - Subject

Last updated

Was this helpful?