RxJava和Retrofit结合使用

Posted 顾明伟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RxJava和Retrofit结合使用相关的知识,希望对你有一定的参考价值。

前言:

前段时间花了点时间学了一下RxJava和Retrofit2,后面在实践中被没有用到,今天一看,呃,都基本上忘掉了。

在这里总结记录一下。

这里调用豆瓣的电影接口拉取一些数据

URL:https://api.douban.com/v2/movie/


一、只用Retrofit2发起网络请求

1.给对应的URL定义一个Java接口

public interface MovieService 

    @GET("top250")//start,count 是接口的参数
    Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);

2.用Retrofit 实例调用接口

创建实例

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(url)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
MovieService movieService = retrofit.create(MovieService.class);

发起请求

Call<MovieEntity> call = movieService.getTopMovie(0, 10);
call.enqueue(new Callback<MovieEntity>() 
      @Override
      public void onResponse(Call<MovieEntity> call, Response<MovieEntity> response) 
          Toast.makeText(getBaseContext(), "success=" + response.body().toString(), Toast.LENGTH_SHORT).show();
      

      @Override
      public void onFailure(Call<MovieEntity> call, Throwable t) 
          Toast.makeText(getBaseContext(), "error=" + t.getMessage(), Toast.LENGTH_SHORT).show();
      
);
用到的实体类

public class MovieEntity implements Serializable 

    private Long mId;

    private String mTitle;

    private String mSummary;

    public Long getmId() 
        return mId;
    

    public void setmId(Long mId) 
        this.mId = mId;
    

    public String getmTitle() 
        return mTitle;
    

    public void setmTitle(String mTitle) 
        this.mTitle = mTitle;
    

    public String getmSummary() 
        return mSummary;
    

    public void setmSummary(String mSummary) 
        this.mSummary = mSummary;
    


二、用RxJava与Retrofit2配合使用

1.把接口对应的Java接口修改如下

public interface MovieService 

//    @GET("top250")
//    Call<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);

    @GET("top250")
    Observable<HttpResult<List<Subject>>> getTopMovie(@Query("start") int start, @Query("count") int count);

2.发起网络请求修改如下,不用Retrofit2的Call回调了,改用RxJava的异步通知机制

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
MovieService movieService = retrofit.create(MovieService.class);
//Call<MovieEntity> call = movieService.getTopMovie(0, 10);
//call.enqueue(new Callback<MovieEntity>() 
//@Override
//public void onResponse(Call<MovieEntity> call, Response<MovieEntity> response) 
//    Toast.makeText(getBaseContext(), "success=" + response.body().toString(), Toast.LENGTH_SHORT).show();
//
//
//@Override
//public void onFailure(Call<MovieEntity> call, Throwable t) 
//    Toast.makeText(getBaseContext(), "error=" + t.getMessage(), Toast.LENGTH_SHORT).show();
//
//);
movieService.getTopMovie(0, 1)
      .subscribeOn(Schedulers.io())
      .observeOn(androidSchedulers.mainThread())
      .subscribe(new Subscriber<HttpResult<List<Subject>>>() 
          @Override
          public void onCompleted() 
          

          @Override
          public void onError(Throwable e) 

          

          @Override
          public void onNext(HttpResult<List<Subject>> listHttpResult) 
              Toast.makeText(getBaseContext(), "result=" + listHttpResult.getTitle(), Toast.LENGTH_SHORT).show();
          
      );
3.用到的HttpResult,Subject。这里用这两个类代替了之前的MovieEntity

HttpResult.java

public class HttpResult<T> 

    private int count;

    private int start;

    private int total;

    private String title;

    private T subjects;

    public int getCount() 
        return count;
    

    public void setCount(int count) 
        this.count = count;
    

    public int getStart() 
        return start;
    

    public void setStart(int start) 
        this.start = start;
    

    public int getTotal() 
        return total;
    

    public void setTotal(int total) 
        this.total = total;
    

    public String getTitle() 
        return title;
    

    public void setTitle(String title) 
        this.title = title;
    

    public T getSubjects() 
        return subjects;
    

    public void setSubjects(T subjects) 
        this.subjects = subjects;
    
Subject.java

public class Subject 

    private String id;
    private String alt;
    private String year;
    private String title;
    private String original_title;
    private List<String> genres;
    private List<Cast> casts;
    private List<Cast> directors;
    private Avatars images;

    @Override
    public String toString() 
        return "Subject.id=" + id
                + " Subject.title=" + title
                + " Subject.year=" + year
                + " Subject.originalTitle=" + original_title + casts.toString() + directors.toString() + " | ";
    

    public String getId() 
        return id;
    

    public void setId(String id) 
        this.id = id;
    

    public String getAlt() 
        return alt;
    

    public void setAlt(String alt) 
        this.alt = alt;
    

    public String getYear() 
        return year;
    

    public void setYear(String year) 
        this.year = year;
    

    public String getTitle() 
        return title;
    

    public void setTitle(String title) 
        this.title = title;
    

    public String getOriginal_title() 
        return original_title;
    

    public void setOriginal_title(String original_title) 
        this.original_title = original_title;
    

    public List<String> getGenres() 
        return genres;
    

    public void setGenres(List<String> genres) 
        this.genres = genres;
    

    public List<Cast> getCasts() 
        return casts;
    

    public void setCasts(List<Cast> casts) 
        this.casts = casts;
    

    public List<Cast> getDirectors() 
        return directors;
    

    public void setDirectors(List<Cast> directors) 
        this.directors = directors;
    

    public Avatars getImages() 
        return images;
    

    public void setImages(Avatars images) 
        this.images = images;
    

    private class Cast 
        private String id;
        private String name;
        private String alt;
        private Avatars avatars;

        public String getId() 
            return id;
        

        public void setId(String id) 
            this.id = id;
        

        public String getName() 
            return name;
        

        public void setName(String name) 
            this.name = name;
        

        public String getAlt() 
            return alt;
        

        public void setAlt(String alt) 
            this.alt = alt;
        

        public Avatars getAvatars() 
            return avatars;
        

        public void setAvatars(Avatars avatars) 
            this.avatars = avatars;
        

        @Override
        public String toString() 
            return "cast.id=" + id + " cast.name=" + name + " | ";
        
    

    private class Avatars 
        private String small;
        private String medium;
        private String large;

        public String getSmall() 
            return small;
        

        public void setSmall(String small) 
            this.small = small;
        

        public String getMedium() 
            return medium;
        

        public void setMedium(String medium) 
            this.medium = medium;
        

        public String getLarge() 
            return large;
        

        public void setLarge(String large) 
            this.large = large;
        
    
用到的依赖

dependencies 
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'io.reactivex:rxjava:1.1.0'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.jakewharton:butterknife:7.0.1'

参考链接:

http://gank.io/post/56e80c2c677659311bed9841


DEMO下载

以上是关于RxJava和Retrofit结合使用的主要内容,如果未能解决你的问题,请参考以下文章

RxJava和Retrofit结合使用

RxJava和Retrofit结合使用

Retrofit结合RxJava使用说明

RxJava开发精要8 – 与REST无缝结合-RxJava和Retrofit

RxJava 与 Retrofit 结合的最佳实践

retrofit和RxJava结合