In the previous post we wrote a HelloWorld program where we created a publisher using Observable and subscribed to it. Let’s extend this.
Let’s have a collection of cities. We would like to get the temperature of these cities. To begin with let’s keep it simple, and just generate a random number as the temperature of these cities. So our publisher will loop through the collection and generate a random number for each city and push it to the subscriber. And here’s the code.
package com.healthycoder; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import java.util.Arrays; import java.util.List; public class HelloWorld { private static List<String> cities = Arrays.asList("Chennai","London","Paris","Rome"); public static void main(String[] args) throws Exception{ Observable<String> producer = Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(ObservableEmitter<String> observableEmitter) throws Exception { for(String city : cities){ String result = "Temperature of " + city + " is " + Math.random()*50 + " deg celsius"; observableEmitter.onNext(result); } } }); producer.subscribe((result) -> System.out.println(result)); } }
We have created an Observable using the create() method. The create() method accepts an instance of ObservableOnSubscribe that has a subscribe() method. The subscribe() method is called when we create a subscriber. What’s interesting is the subscribe() method itself. If you want to push data to the subscriber we call the onNext() method.
Here’s the output when I ran the code.
Temperature of Chennai is 29.35073996653142 deg celsius Temperature of London is 43.78882107284912 deg celsius Temperature of Paris is 46.73974371173081 deg celsius Temperature of Rome is 43.40540311264642 deg celsius
Let’s bring in lambda expressions and make this code more readable. My publisher with lambda syntax looks like this now.
Observable<String> producer = Observable.create(emitter -> { for(String city : cities){ String result = "Temperature of " + city + " is " + Math.random()*50 + " deg celsius"; emitter.onNext(result); } });
The code is lot better now.