관리 메뉴

꿀맛코딩

What is ConnectableObservable? 본문

공부방/RxKotlin

What is ConnectableObservable?

soycrab 2019. 7. 23. 21:04

ConnectableObservable 이란?

 

Hot Observable 과 Cold Observable 둘다 사용 가능한 Observable 로서 

 

기능은 다음과 같다. 

 

1.  Cold Observable < - >  Hot Observable 변환 가능

 

2. 한개의 Observable에 여러개의 구독을 할수 있으며, 

   기존의 Cold Observable 처럼 구독시 처음부터 아이템을 배출 하는게 아니라

   이전에 호출된 모든 Observer 를 연결 하고 모든 Observer 에게 단일 푸쉬를 전달한다.

 

fun simpleConnectableObservable() {
     val connectableObservable = listOf("Stream1", "Stream2", "Stream3", "Stream4").toObservable().publish() (1)
     connectableObservable.subscribe{ println("SubScription 1: $it") (2)
     connectableObservable.map { it.reversed()}.subscribe{ println("SubScription 2 $it") (3)
     connectableObservable.connect()  (4)
     connectableObservable.subscribe{ println("Subscription 3: $it") (5)
}

 

코드를 차근 차근 살펴 보자 

 

(1)  list를 toObservable을 이용하여 Observable 을 생성하고,

      publish 메서드를 이용하여 Cold Observerble 을 ConnectableObservable로 변환 했다. 

 

(2) connectableObservable 을 구독하고 요소들을 print 할수 있게 했다. 

 

(3) map 을 이용하여 요소들을 역으로 바꾸고 print 할수 있게 했다. 

 

(4) connect를 이용하여 이전에 Subsription한 모든 Observer들 에게 데이터를 배출하기 시작한다. 

 

(5) connectableObservable 을 구독하고 요소들을 print  할수 있게 했다. 

 

 

결과 

그림 1

그림 1을 보면서 설명 하겠습니다.

결과물을 보면 

(2) Observer 가 출력이 되고 

다음으로 (3) Observer 가 String 을 역으로 출력을 하는데 

(4) 번 Observer 는 동작을 하지 않았다. 

이유는 ConnectableObservable은 (4) 을 한순간에 이전에 자신을 Subscribe 한 Observer 들에게 

이미 배출 이 끝낫으므로 (5) Observer 는 데이터를 받지 못한다.  

 

이전의 from 이나 just 같은 경우는 subscribe 하면, 처음부터 데이터를 배출 했지만,

ConnectableObservable은 기존 배출을 유지하며 Observer 들에게 데이터를 전달한다.

반응형

'공부방 > RxKotlin' 카테고리의 다른 글

defualtIfEmpty and switchIfEmpty  (0) 2019.07.29
What is BackPressure? (BackPressure 란?)  (0) 2019.07.25
observable.from and observable.just  (0) 2019.07.23
cold observable and hot observable  (0) 2019.07.23
What is Observable?  (0) 2019.07.23
Comments