官术网_书友最值得收藏!

Cold Observable

When the Observable itself creates the procedure or, say, Observable produces the data stream itself, it is said to be cold Observable. Generally Observable is lazy in nature, meaning it only emits the data when any Observer subscribes to it. Cold Observable always starts a fresh execution for each subscriber. 

In other words, cold Observable emits separate data/event streams for individual Observers. All examples we have seen so far were of a cold Observable type, where we have created a data stream with the just() or create() method. Let's see how cold Observable works for more than one Observer subscribed, with the following example.

public class RxJavaColdObservable {
public static void main(String[] args) {
Observable<String> source =
Observable.just("One","Two","Three","Four","Five");
//first observer
source.filter(data->data.contains("o"))
.subscribe(data -> System.out.println("Observer 1 Received:" + data));
//second observer
source.subscribe(data -> System.out.println("Observer 2 Received:" + data));
}
}

In this code, the data is created by Observable itself so it is called cold Observable.  We have subscribed two different Observers. When you run this code, you will get an output as follows:

Cold Observable provides a separate data stream for each Observer so when we applied the filter for first Observer there is no effect in the second Observer. Also if there are more than one Observer, then Observable will emit the sequence of data to all observers one by one.

主站蜘蛛池模板: 苗栗市| 望城县| 观塘区| 临安市| 古蔺县| 宁远县| 通江县| 凤庆县| 刚察县| 黑水县| 洪泽县| 毕节市| 永城市| 永春县| 卢龙县| 读书| 囊谦县| 凤阳县| 蚌埠市| 抚松县| 景东| 武穴市| 峨边| 金堂县| 巍山| 开化县| 丹寨县| 游戏| 昆山市| 临沧市| 山西省| 沾化县| 葵青区| 淮安市| 鹿邑县| 惠来县| 巴楚县| 清河县| 科尔| 大港区| 闵行区|