I'm new to RxJava and I'm trying to understand the best/recommended way to perform long running tasks asynchronously (e.g. network requests). I've read through a lot of examples online but would appreciate some feedback.
The following code works (it prints 'one', 'two', then 'User: x' ... etc) but should I really be creating/managing Threads manually?
Thanks in advance!
public void start() throws Exception {
System.out.println("one");
observeUsers()
.flatMap(users -> Observable.from(users))
.subscribe(user -> System.out.println(String.format("User: %s", user.toString()));
System.out.println("two");
}
Observable<List<User>> observeUsers() {
return Observable.<List<User>>create(s -> {
Thread thread = new Thread(() -> getUsers(s));
thread.start();
});
}
void getUsers(final Subscriber s) {
s.onNext(userService.getUsers());
s.onCompleted();
}
// userService.getUsers() fetches users from a web service.
Instead of managing your own thread try using the defer()
operator. Meaning replace observeUsers()
with Observable.defer(() -> Observable.just(userService.getUsers()))
. Then you can use the RxJava Schedulers to control what threads are used during subscription and observation. Here's your code modified with the above suggestions.
Observable.defer(() -> Observable.just(userService.getUsers()))
.flatMap(users -> Observable.from(users))
.subscribeOn(Schedulers.newThread())
.observeOn(Schedulers.trampoline())
.subscribe(user -> System.out.println(String.format("User: %s", user.toString()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With