Skip to content

Commit ff5a585

Browse files
committed
Added explanation of defer
1 parent b7700ea commit ff5a585

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

Part 2 - Sequence Basics/1. Creating a sequence.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,39 @@ Output
8080
Error: java.lang.Exception: Oops
8181
```
8282

83+
### Observable.defer
84+
85+
`defer` doesn't define a new kind of observable, but allows you to declare that a source observable should be created when a subscriber arrives. Consider how you would create an observable that returns the current time and terminates. You are emitting a single value, so it sounds like a case for `just`.
86+
87+
```java
88+
Observable<Long> now = Observable.just(System.currentTimeMillis());
89+
90+
now.subscribe(System.out::println);
91+
Thread.sleep(1000);
92+
now.subscribe(System.out::println);
93+
```
94+
Output
95+
```
96+
1431443908375
97+
1431443908375
98+
```
99+
100+
Notice how the two subscribers, 1 second apart, see the same time. That is because the value for the time aquired once, when the observable is created. What you want is for the time to be aquired when a subscriber asks for it.
101+
102+
```java
103+
Observable<Long> now = Observable.defer(() ->
104+
Observable.just(System.currentTimeMillis()));
105+
106+
now.subscribe(System.out::println);
107+
Thread.sleep(1000);
108+
now.subscribe(System.out::println);
109+
```
110+
Output
111+
```
112+
1431444107854
113+
1431444108858
114+
```
115+
83116
### Observable.create
84117

85118
`create` is a very versatile function for creating observables. Let have a look at the signature.

0 commit comments

Comments
 (0)