# Hello World!
The following sample implementations of âHello Worldâ in Java, Groovy, Clojure, and Scala create an Observable from a list of Strings, and then subscribe to this Observable with a method that prints âHello _String_!â for each string emitted by the Observable.
You can find additional code examples in the `/src/examples` folders of each [language adaptor](https://github.com/ReactiveX/):
* [RxGroovy examples](https://github.com/ReactiveX/RxGroovy/tree/1.x/src/examples/groovy/rx/lang/groovy/examples)
* [RxClojure examples](https://github.com/ReactiveX/RxClojure/tree/0.x/src/examples/clojure/rx/lang/clojure/examples)
* [RxScala examples](https://github.com/ReactiveX/RxScala/tree/0.x/examples/src/main/scala)
### Java
```java
public static void hello(String... args) {
Flowable.fromArray(args).subscribe(s -> System.out.println("Hello " + s + "!"));
}
```
If your platform doesn't support Java 8 lambdas (yet), you have to create an inner class of ```Consumer``` manually:
```java
public static void hello(String... args) {
Flowable.fromArray(args).subscribe(new Consumer() {
@Override
public void accept(String s) {
System.out.println("Hello " + s + "!");
}
});
}
```
```java
hello("Ben", "George");
Hello Ben!
Hello George!
```
### Groovy
```groovy
def hello(String[] names) {
Observable.from(names).subscribe { println "Hello ${it}!" }
}
```
```groovy
hello("Ben", "George")
Hello Ben!
Hello George!
```
### Clojure
```clojure
(defn hello
[&rest]
(-> (Observable/from &rest)
(.subscribe #(println (str "Hello " % "!")))))
```
```
(hello ["Ben" "George"])
Hello Ben!
Hello George!
```
### Scala
```scala
import rx.lang.scala.Observable
def hello(names: String*) {
Observable.from(names) subscribe { n =>
println(s"Hello $n!")
}
}
```
```scala
hello("Ben", "George")
Hello Ben!
Hello George!
```
# How to Design Using RxJava
To use RxJava you create Observables (which emit data items), transform those Observables in various ways to get the precise data items that interest you (by using Observable operators), and then observe and react to these sequences of interesting items (by implementing Observers or Subscribers and then subscribing them to the resulting transformed Observables).
## Creating Observables
To create an Observable, you can either implement the Observable's behavior manually by passing a function to [`create(â¯)`](http://reactivex.io/documentation/operators/create.html) that exhibits Observable behavior, or you can convert an existing data structure into an Observable by using [some of the Observable operators that are designed for this purpose](Creating-Observables).
### Creating an Observable from an Existing Data Structure
You use the Observable [`just(â¯)`](http://reactivex.io/documentation/operators/just.html) and [`from(â¯)`](http://reactivex.io/documentation/operators/from.html) methods to convert objects, lists, or arrays of objects into Observables that emit those objects:
```groovy
Observable o = Observable.from("a", "b", "c");
def list = [5, 6, 7, 8]
Observable o2 = Observable.from(list);
Observable o3 = Observable.just("one object");
```
These converted Observables will synchronously invoke the [`onNext(â¯)`](Observable#onnext-oncompleted-and-onerror) method of any subscriber that subscribes to them, for each item to be emitted by the Observable, and will then invoke the subscriberâs [`onCompleted(â¯)`](Observable#onnext-oncompleted-and-onerror) method.
### Creating an Observable via the `create(â¯)` method
You can implement asynchronous i/o, computational operations, or even âinfiniteâ streams of data by designing your own Observable and implementing it with the [`create(â¯)`](http://reactivex.io/documentation/operators/create.html) method.
#### Synchronous Observable Example
```groovy
/**
* This example shows a custom Observable that blocks
* when subscribed to (does not spawn an extra thread).
*/
def customObservableBlocking() {
return Observable.create { aSubscriber ->
50.times { i ->
if (!aSubscriber.unsubscribed) {
aSubscriber.onNext("value_${i}")
}
}
// after sending all values we complete the sequence
if (!aSubscriber.unsubscribed) {
aSubscriber.onCompleted()
}
}
}
// To see output:
customObservableBlocking().subscribe { println(it) }
```
#### Asynchronous Observable Example
The following example uses Groovy to create an Observable that emits 75 strings.
It is written verbosely, with static typing and implementation of the `Func1` anonymous inner class, to make the example more clear:
```groovy
/**
* This example shows a custom Observable that does not block
* when subscribed to as it spawns a separate thread.
*/
def customObservableNonBlocking() {
return Observable.create({ subscriber ->
Thread.start {
for (i in 0..<75) {
if (subscriber.unsubscribed) {
return
}
subscriber.onNext("value_${i}")
}
// after sending all values we complete the sequence
if (!subscriber.unsubscribed) {
subscriber.onCompleted()
}
}
} as Observable.OnSubscribe)
}
// To see output:
customObservableNonBlocking().subscribe { println(it) }
```
Here is the same code in Clojure that uses a Future (instead of raw thread) and is implemented more consisely:
```clojure
(defn customObservableNonBlocking []
"This example shows a custom Observable that does not block
when subscribed to as it spawns a separate thread.
returns Observable"
(Observable/create
(fn [subscriber]
(let [f (future
(doseq [x (range 50)] (-> subscriber (.onNext (str "value_" x))))
; after sending all values we complete the sequence
(-> subscriber .onCompleted))
))
))
```
```clojure
; To see output
(.subscribe (customObservableNonBlocking) #(println %))
```
Here is an example that fetches articles from Wikipedia and invokes onNext with each one:
```clojure
(defn fetchWikipediaArticleAsynchronously [wikipediaArticleNames]
"Fetch a list of Wikipedia articles asynchronously.
return Observable of HTML"
(Observable/create
(fn [subscriber]
(let [f (future
(doseq [articleName wikipediaArticleNames]
(-> subscriber (.onNext (http/get (str "http://en.wikipedia.org/wiki/" articleName)))))
; after sending response to onnext we complete the sequence
(-> subscriber .onCompleted))
))))
```
```clojure
(-> (fetchWikipediaArticleAsynchronously ["Tiger" "Elephant"])
(.subscribe #(println "--- Article ---\n" (subs (:body %) 0 125) "...")))
```
Back to Groovy, the same Wikipedia functionality but using closures instead of anonymous inner classes:
```groovy
/*
* Fetch a list of Wikipedia articles asynchronously.
*/
def fetchWikipediaArticleAsynchronously(String... wikipediaArticleNames) {
return Observable.create { subscriber ->
Thread.start {
for (articleName in wikipediaArticleNames) {
if (subscriber.unsubscribed) {
return
}
subscriber.onNext(new URL("http://en.wikipedia.org/wiki/${articleName}").text)
}
if (!subscriber.unsubscribed) {
subscriber.onCompleted()
}
}
return subscriber
}
}
fetchWikipediaArticleAsynchronously("Tiger", "Elephant")
.subscribe { println "--- Article ---\n${it.substring(0, 125)}" }
```
Results:
```text
--- Article ---
Tiger - Wikipedia, the free encyclopedia ...
--- Article ---
Elephant - Wikipedia, the free encyclopedia return stringValue + "_xform"})
.subscribe({ println "onNext => " + it})
}
```
This results in:
```text
onNext => value_10_xform
onNext => value_11_xform
onNext => value_12_xform
onNext => value_13_xform
onNext => value_14_xform
```
Here is a marble diagram that illustrates this transformation:
This next example, in Clojure, consumes three asynchronous Observables, including a dependency from one to another, and emits a single response item by combining the items emitted by each of the three Observables with the [`zip`](http://reactivex.io/documentation/operators/zip.html) operator and then transforming the result with [`map`](http://reactivex.io/documentation/operators/map.html):
```clojure
(defn getVideoForUser [userId videoId]
"Get video metadata for a given userId
- video metadata
- video bookmark position
- user data
return Observable