Skip to content

Commit 1290ebd

Browse files
committed
4.1 Added unsubscribeOn
1 parent 9e5cb08 commit 1290ebd

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Part 4 - Concurrency/1. Scheduling and threading.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,41 @@ We can see here that events start on thread that calls `onNext` and stay on that
160160

161161
This is very useful if you, as the consumer of an observable, know that processing is time-consuming and you don't want to block the producing thread. A typical case for this is applications with a GUI. Handlers to GUI events are invoked on the GUI thread by default. In order not to have your application freeze for the duration of the processing, you can take the processing to another thread. You can use `observeOn` again to return to the GUI thread, when the data is ready to be displayed.
162162

163+
### unsubscribeOn
164+
165+
As we have seen, some observables depend on resources which are leased on subscription and released when subscriptions end. Typically, releasing resources is cheap, but there can be cases where releasing a resource may require ceremony, e.g. coordinating over a network. If you need control over the thread that will execute the unsubscription code, you can define that with the `unsubscribeOn` method.
166+
167+
```java
168+
Observable<Object> source = Observable.using(
169+
() -> {
170+
System.out.println("Subscribed on " + Thread.currentThread().getId());
171+
return Arrays.asList(1,2);
172+
},
173+
(ints) -> {
174+
System.out.println("Producing on " + Thread.currentThread().getId());
175+
return Observable.from(ints);
176+
},
177+
(ints) -> {
178+
System.out.println("Unubscribed on " + Thread.currentThread().getId());
179+
}
180+
);
181+
182+
source
183+
.unsubscribeOn(Schedulers.newThread())
184+
.subscribe(System.out::println);
185+
```
186+
Output
187+
```
188+
Subscribed on 1
189+
Producing on 1
190+
1
191+
2
192+
Unubscribed on 11
193+
```
194+
195+
The `using` method executes 3 functions, one that leases a resource, one that uses it and one the releases it. With `unsubscribeOn` we only affected the function that releases the resource.
196+
197+
163198
## Schedulers
164199

165200
The `observeOn` and `subscribeOn` methods take as an argument a [Scheduler](http://reactivex.io/RxJava/javadoc/rx/Scheduler.html). A `Scheduler`, as the name suggests, is a tool that can schedule individual actions to be performed. The specifics of how the action will be invoked depends on the implementation of the scheduler used. You can create your own implementation of scheduler, but Rx already has you covered with a set of Schedulers for the common cases. You can get the existing implementations from the factory methods on [Schedulers](http://reactivex.io/RxJava/javadoc/rx/schedulers/Schedulers.html).

0 commit comments

Comments
 (0)