retrofit2+RxJava简单使用

刚学习Android的网络开发,记录起来,作个纪念。

资源:

retrofit2学习: http://square.github.io/retrofit/

RxJAVA学习: http://gank.io/post/560e15be2dca930e00da1083

使用Android Studio开发。

1. 配置build.gradle

	compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    compile 'io.reactivex:rxjava:1.1.3'
    compile 'io.reactivex:rxandroid:1.1.0'

2.  后台服务代码(Python)

只为测试,写得比较简单.使用的是bottle轻量级服务框架

设置了一个记数器,每次请求,返回的数都将加1

import json
from bottle import route, run
 
@route('/app/v1/game/new')
def new_game():
    new_game.counter += 1
    return json.dumps(["liuzhiliang" + str(new_game.counter)])

if __name__ == '__main__':
    # 定义记数器
    new_game.counter = 0
    # 运行服务
    run(host='0.0.0.0', port=8421)

3. 设置接口

设置两种接口类型,一种是Call,使用retrofit2自带的处理,一种是rx.Observable, 使用RxJAVA调用方式。 需要注意的是,他们调的是同一个接口!

package com.example.jerome.chess;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;
import rx.Observable;

/**
 * Created by jerome on 16/8/25.
 */
public interface GameApi {
    @GET("/app/v1/game/new")
    Observable> newGame();
    @GET("/app/v1/game/new")
    Call> newGame1();
}

4. 获取接口实现

数据统一使用Gson来转换。

public  static   T createService(String baseUrl, Class cls){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //rxjava 时添加
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return  retrofit.create(cls);
    }

调用生成代码

GameApi service = createService(baseUrl, GameApi.class);

5. Call调用方式封装

public static  void RunCall(GameApi service){
        service.newGame1().enqueue(
                new Callback>(){
                    @Override
                    public void onResponse(Call> call, Response> response) {
                        for(String a : response.body())
                            System.out.println("Call: " +a);
                    }
                    @Override
                    public void onFailure(Call> call, Throwable t) {
                        System.out.println("1 error: " + t.getMessage());

                    }
                }
        );
    }

6. RxJAVA调用方式封装

public static  void RunRxJava(GameApi service){
        service.newGame()
        .subscribeOn(Schedulers.io())
        .subscribe(new Subscriber>() {
            @Override
            public void onCompleted() {
                System.out.println("onCompleted: ");
            }

            @Override
            public void onError(Throwable e) {
                System.out.println("onError:" + e.getMessage());
            }

            @Override
            public void onNext(List strings) {
                for (String a : strings)
                    System.out.println("RXJAVA: " + a);
            }
        });
    }

7. 测试函数

public static void main(String[] args){
        String baseUrl = "http://127.0.0.1:8421/";
        GameApi service = createService(baseUrl, GameApi.class);
        for(int i = 0; i < 5; i++)
            RunCall(service);
        for(int i = 0; i < 5; i++)
            RunRxJava(service);

    }

8. 程序输出

Call: liuzhiliang5
Call: liuzhiliang2
Call: liuzhiliang1
Call: liuzhiliang4
RXJAVA: liuzhiliang6
Call: liuzhiliang3
onCompleted: 
RXJAVA: liuzhiliang7
onCompleted: 
RXJAVA: liuzhiliang8
onCompleted: 
RXJAVA: liuzhiliang9
onCompleted: 
RXJAVA: liuzhiliang10
onCompleted: 

Process finished with exit code 0




你可能感兴趣的:(android)