java - Recommended way to execute async tasks with RXJava -
i'm new rxjava , i'm trying understand best/recommended way perform long running tasks asynchronously (e.g. network requests). i've read through lot of examples online appreciate feedback.
the following code works (it prints 'one', 'two', 'user: x' ... etc) should 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 web service.
instead of managing own thread try using defer()
operator. meaning replace observeusers()
observable.defer(() -> observable.just(userservice.getusers()))
. can use rxjava schedulers control threads used during subscription , observation. here's code modified 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()));
Comments
Post a Comment