The just()
method emits its parameter(s) as OnNext
notifications, and after that, it emits an OnCompleted
notification.
Observable.just('S').subscribe(System.out::println);
Or a sequence of letters:
Observable .just('R', 'x', 'J', 'a', 'v', 'a') .subscribe( System.out::print, System.err::println, System.out::println );
The first piece of code prints S
and a new line, and the second prints the letters on a single line and adds a new line on completion. The method allows up to nine arbitrary values (objects of the same type) to be observed through reactive means. For example, say we have this simple User
class:
public static class User { private final String forename; private final String lastname; public User(String forename, String lastname) { this.forename = forename; this.lastname = lastname; } public String getForename() { return this.forename; } public String getLastname() { return this.lastname; } }
We can print the full name of a User
instance like this:
Observable .just(new User("Dali", "Bali")) .map(u -> u.getForename() + " " + u.getLastname()) .subscribe(System.out::println);
This is not very practical but showcases putting data in the Observable
instance context and taking advantage of the map()
method. Everything can become an event.
There are a few more convenient factory methods, usable in all kinds of situations. Let's take a look at them in the next section.
The source code of the example of the Observable.just()
method can be viewed/downloaded at https://github.com/meddle0x53/learning-rxjava/blob/master/src/main/java/com/packtpub/reactive/chapter03/CreatingObservablesUsingJust.java.
3.144.242.235