Reputation: 3161
My code is:
RestClient client = new RestClient();
Disposable subscribe = client.getApiMovie().getTopRated()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe( data -> { Log.d("mytag", data.body().toString()) });
Is that code right. PS: I'm using Android Studio 2, how can I set it up in order to use lambda expression?
my RestClient constructor:
//what adapter shall I use?
public RestClient(){
if( client == null ) {
client = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(getHttpClient())
.build();
}
}
build.gradle:
android {
compileSdkVersion 24
buildToolsVersion "24.0.3"
defaultConfig {
applicationId "com.example.username.sunshine.app"
minSdkVersion 21
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
jackOptions {
enabled true
}
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Lambda syntax should now work by adding jackOptions and compileOptions
Upvotes: 0
Views: 845
Reputation: 5148
If you are gonna use Retrofit with Rx, don't forget to add call adapter for Rx.
client = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(getHttpClient())
.build();
If you are doing like this, you are doing right. For better mapping, rest client should return an Observable with your object, like Observable<List<Movie>> getApiMovie();
and this will return a list of movies. Movie object should contains all properties from api annotated with @SerializedName("objectName")
.
Because you are using RxJava 2, use .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
with dependency compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
. More details here here.
Upvotes: 1
Reputation: 3282
Yes, it is right, your api client has to return Observable. Retrofit library can utilize 'adapter factory' for returning observables. In case this is your custom RestClient and you create Observable manually, don't forget to use Observable.defer(()- > yourTask). There is a library called Retrolambda, it allows to use lambdas, but, I faced issue, that it is not working with latest AndroidStudio and AndroidStudio suggest to use Jack instead. Right now I use Retrolambda.
Upvotes: 1