jmickela
jmickela

Reputation: 663

Using rxjava I can't get retrofit off the main thread

Simplified code is below, s is a subscriber that matches the return type of my end point. No matter what I do I get a network on main thread exception. Some tutorials don't even mention threads here saying retrofit handles it automatically when you use rxjava, but things seem to be going the other way for me, I can't seem to get it off the main thread.

PostInterface p = getRestAdapter().create(PostInterface.class);

p.getFeedForUser()
    .observeOn(Schedulers.newThread())
    .subscribeOn(AndroidSchedulers.mainThread())
    .subscribe(s);

Edit:

I have also tried this code (posted below):

p.getFeedForUser()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.newThread())
    .subscribe(s);

I have also tried it without subscribing on a thread. I get the networking on main thread exception every time.

Upvotes: 1

Views: 1638

Answers (2)

jmickela
jmickela

Reputation: 663

Turns out I was using an older version of Retrofit, as soon as I switched to a newer version it started working properly.

Upvotes: 1

Danila Grigorenko
Danila Grigorenko

Reputation: 423

You should observeOn in main thread, subscribe on new thread

p.getFeedForUser()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.newThread())
    .subscribe(s);

Upvotes: 5

Related Questions