emmby
emmby

Reputation: 100464

Using a function to generate on object on a background thread using RxJava Observables

I'm playing around with RxJava and trying to figure out how run a method on a background thread and deal with the results on the foreground thread. I stumbled across a solution but wanted to get a sanity check and see if there was a better way, since there seem to be a lot of different ways to compose Observables to do similar things.

Here's what I have:

    Observable.defer(
        () -> Observable.just(
            // A. Should run on Scheduler.newThread
            db.query(
                false, DATABASE_TABLE, null,
                null, null, null, null, null,
                null)))
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(
        Subscribers.create(
            // B. Should run on AndroidSchedulers.mainThread
            cursor -> adapter.swapCursor(cursor)
        ));

The code works as expected. A runs on the background thread and B runs on the main thread.

My question is, this seems reasonable enough but is there a more elegant way to do this?

Upvotes: 1

Views: 441

Answers (1)

lopar
lopar

Reputation: 2442

defer is a decent enough way to do it, but with the optional RxAsyncUtil lib, you can use the slightly nicer fromFunc0, like this:

Observable.fromFunc0(() -> db.query(...))
    .subscribeOn(... etc.

also, you don't have to use Subscribers.create, since one of the main overloads of subscribe takes a single action for onNext.

So, your subscribe could become:

    .subscribe(cursor -> { adapter.swapCursor(cursor) }) 

(not 100% sure if the {}s are necessary with the java8 lambdas. they may not be if swapCursor is void... try both?)

so, all together:

Observable.fromFunc0(() -> db.query(
    false, DATABASE_TABLE, null, null, null, null, null, null, null))
    .scheduleOn(Schedulers.newThread())
    .observeOn(Schedulers.mainThread())
    .subscribe(cursor -> { adapter.swapCursor(cursor) })

seems like a pretty tight implementation. :)

Upvotes: 1

Related Questions