Retrofit2 + RxJava2 + RxAndroid error
RxJavaCallAdapter
returns a RxJava 1 Observable
. You should use RxJava2CallAdapter
for RxJava2. Looks like that is not in an official retrofit release yet, but is in the 2.1.1 snapshot. You can either compile the adapter yourself, or pull the dependencies off the sonatype snapshot repo.
Add the following to your repositories
section in your build.gradle
--
repositories {
// Other repos...
maven {
url = "https://oss.sonatype.org/content/repositories/snapshots/"
}
}
Update your retrofit dependencies to the 2.1.1-SNAPSHOT
version. Note that we also change adapter-rxjava
to adapter-rxjava2
--
compile 'com.squareup.retrofit2:retrofit:2.1.1-SNAPSHOT'
compile 'com.squareup.retrofit2:converter-gson:2.1.1-SNAPSHOT'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.1.1-SNAPSHOT'
and update your retrofit builder to use RxJava2CallAdapterFactory
--
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(baseUrl)
.build();
When 2.1.1 is released, you can go back to the regular dependencies.
If you do not want to update the retrofit version. Here is one very good library to convert to and from RxJava1.x
to RxJava2.x
objects.
First, add thiscompile "com.github.akarnokd:rxjava2-interop:0.10.2"
to build.gradle
and Use methodRxJavaInterop.toV2Observable(observableRx1)
to convert to Rx2 Observables.
The fact that adapter has version 2.*.*
does not mean that it is intended for use with RxJava 2
You should use the official adapter for the second version of RxJava:
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' // works with RxJava 2
Then you can add factory:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
Here is the full answer.
Here is my build.gradle setting, perhaps this would help others
depencies{
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.squareup.okhttp3:okhttp:3.8.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'}