[RxSwift] Subjects & Relays

Junyoung Park·2022년 8월 31일
0

RxSwift

목록 보기
3/25
post-thumbnail

RxSwift Beginners Episode 3 - Subjects and Relays

Subjects & Relays

Subject

  • Observable + Observer
  • 실시간으로 Observable에 구독을 추가할 수 있는 방법

PublishSubject

  • 새로운 아이템만 주는 PublishSubject
let publishSubject = PublishSubject<String>()

let observer1 = publishSubject.subscribe(onNext: { element in
    print("observer1 sees \(element)")
})
publishSubject.onNext("PS E1 1")
// observer1 sees PS E1 1 -> Only observer1 can see this

let observer2 = publishSubject.subscribe(onNext: { element in
    print("observer2 sees \(element)")
})

publishSubject.onNext("PS E1 2")
// observer1 sees PS E1 2
// observer2 sees PS E1 2
// observer1, 2 were watching that event

BehaviorSubject

  • 최근에 가지고 있는 아이템을 주는 BehaviorSubject
  • 초깃값이 있는 게 특징
let behaviorSubject = BehaviorSubject<String>(value: "BS E1 1")

let observer1 = behaviorSubject.subscribe(onNext: { element in
    print("observer1 sees \(element)")
})
// observer1 sees BS E1 1
// behaviorSubject (value) -> Observer attached -> then Observer can see it

ReplaySubject

  • 버퍼 사이즈의 아이템을 주는 ReplaySubject
let replySubject = ReplaySubject<Int>.create(bufferSize: 2)
replySubject.onNext(1)
replySubject.onNext(2)
replySubject.onNext(3)
replySubject.onNext(4)

let observer1 = replySubject.subscribe(onNext: { element in
    print(element)
})
// 3
// 4
// -> only can see lastest buffer-sized elements

AsyncSubject

  • 서브젝트가 완료 이벤트를 받았을 때에만 시퀀스 상의 마지막 이벤트만을 주는 AsyncSubject
let asyncSubject = AsyncSubject<String>()
asyncSubject.onNext("aSub E1 1")
asyncSubject.onNext("aSub E1 2")
asyncSubject.onNext("aSub E1 3")

let observer1 = asyncSubject.subscribe(onNext: { element in
    print(element)
})

asyncSubject.onCompleted()
// aSub E1 3
// asyncSubject can only see completed event-element 

Relays

  • PublishSubjectWrapper 클래스
  • dispose되기 전까지 계속해서 작동 가능
  • completed, error로 인해 종료되지 않기 때문에 Subject와 달리 UI 이벤트를 담당하기 적절함

Publish Relay

  • Publish RelayPublish Subject의 특성처럼 구독한 이후의 값만 감지 가능
let publishRelay = PublishRelay<String>()
publishRelay.accept("pRel E1 1")

let observer1 = publishRelay.subscribe(onNext: { element in
    print(element)
})

publishRelay.accept("pRel E1 2")
// pRel E1 2 -> only see events after its observer has been attached

Behavior Relay

  • Behavior Relay는 초깃값을 가질 수 있고, Publishe Relay와 마찬가지로 계속해서 갱신되는 값을 관찰
let behaviorRelay = BehaviorRelay<String>(value: "bRel E1 1")

let observe1 = behaviorRelay.subscribe(onNext: { element in
    print(element)
})

behaviorRelay.accept("bRel E1 2")
// bRel E1 1 -> Initial event
// bRel E1 2 -> lastest event also would be seen
profile
JUST DO IT

0개의 댓글