Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2.0-Beta1 Read Response from Observable

I am trying to read the httpstatus code e body in the success case of a request. So I created the code below to test but I failed to get the onNext called, I tried to use the okhttp (com.squareup.okhttp.Response) and retrofit Response (retrofit.Response) class, but I couldn't make it work.

Can someone help me to read the body and httpstatus code here? I would like to keep using the Observables. Thanks in advance.

package com.app.rest;

import com.squareup.okhttp.Response;

import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;
import retrofit.http.GET;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class TestApiClient {
    public interface Test {
        @GET("/posts")
        Observable<Response> getPosts();
    }

    public TestApiClient() {
        new Retrofit.Builder()
                .baseUrl("http://jsonplaceholder.typicode.com")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build().create(Test.class).getPosts().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Response>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.toString();
            }

            @Override
            public void onNext(Response response) {
                response.toString();
            }
        });
    }
}
like image 259
BugsBunnyBR Avatar asked Sep 18 '15 13:09

BugsBunnyBR


1 Answers

I got the answer.

import com.squareup.okhttp.ResponseBody;
import retrofit.Response;

...

public Observable<Response<ResponseBody>> xxx(){}
...

Playlist playlist = Playlist.parse(((ResponseBody)response.body()).byteStream());

Actually, response.body() is a Object, You can cast it to another type.In this case, it is ResponseBody.

like image 200
xmaxing Avatar answered Nov 07 '22 04:11

xmaxing