本文源码地址:https://github.com/HelloNanKe/Joke
先看一下Rxjava和Retrofit相关的依赖
compile'io.reactivex.rxjava2:rxjava:2.0.7'
compile'io.reactivex.rxjava2:rxandroid:2.0.1'
compile'com.squareup.retrofit2:retrofit:2.2.0'
compile'com.squareup.retrofit2:converter-gson:2.2.0'
compile'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
本文以来福岛的一个笑话api为例,在这里想他们表示感谢
api为:http://api.laifudao.com/open/xiaohua.json
返回的数据,没有数据头,且返回的内容中夹杂着HTML标签
先看代码吧:
public interfaceApiService {
/**
* 来福笑话接口
*@return List<>
*/
@GET("xiaohua.json")
Observable<List<MyJoke>> getData();
}
在这里需要注意的是,与Retrofit相比不再是Call<List<MyJoke>>,而是使用了Rxjava的Observable<List<MyJoke>> getData();
这里MyJoke使用GsonFormat自动生成的一个实体类。
接下来就是对网络请求进行一下简单的封装了
HttpMethods.java文件
package com.example.nanke.joke;
import com.example.nanke.joke.JavaBean.MyJoke;
import java.util.List;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by zt on 2017/3/10.
*/
public class HttpMethods {
private static final String BASE_URL = "http://api.laifudao.com/open/";
private static final int TIME_OUT=4;
private Retrofit retrofit;
private ApiService apiService;
private HttpMethods() {
/**
* 构造函数私有化
* 并在构造函数中进行retrofit的初始化
*/
OkHttpClient client=new OkHttpClient();
client.newBuilder().connectTimeout(TIME_OUT, TimeUnit.SECONDS);
/**
* 由于retrofit底层的实现是通过okhttp实现的,所以可以通过okHttp来设置一些连接参数
* 如超时等
*/
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
apiService=retrofit.create(ApiService.class);
}
private static class sinalInstance {
public static final HttpMethods instance = new HttpMethods();
}
public static HttpMethods getInstance(){
return sinalInstance.instance;
}
public void getJoke(Observer<List<MyJoke>> observer){
apiService.getData()
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
}
在HttpMethods中,将构造函数私有化是为了实现单例,并向外提供了一个请求数据的方法 getJoke;该方法的参数是一个观察者,接着看一下MainActivity.java文件
package com.example.nanke.joke;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.example.nanke.joke.JavaBean.MyJoke;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<MyJoke> jokes = new ArrayList<>();
private MyAdpter adpter;
private MaterialRefreshLayout materialRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_View);
materialRefreshLayout = (MaterialRefreshLayout) findViewById(R.id.refresh);
getData();
materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
@Override
public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getData();
adpter.refreshData(jokes);
materialRefreshLayout.finishRefresh();
}
}, 2000);
}
});
}
public void getData() {
HttpMethods.getInstance().getJoke(new Observer<List<MyJoke>>() {
Disposable d;
@Override
public void onSubscribe(Disposable d) {
this.d = d;
}
@Override
public void onNext(List<MyJoke> myJokes) {
jokes = myJokes;
adpter = new MyAdpter(myJokes);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adpter);
adpter.notifyDataSetChanged();
Log.d("MAIN", "获取数据完成" + myJokes.size());
}
@Override
public void onError(Throwable e) {
Log.d("MAIN", "error" + e.toString());
d.dispose();
}
@Override
public void onComplete() {
Log.d("MAIN", "onComplete");
d.dispose();
}
});
}
}
重点请看下面这个方法(请忽略那蹩脚的下拉刷新)
public void getData() {
HttpMethods.getInstance().getJoke(new Observer<List<MyJoke>>() {
Disposable d;
@Override
public void onSubscribe(Disposable d) {
this.d = d;
}
@Override
public void onNext(List<MyJoke> myJokes) {
jokes = myJokes;
adpter = new MyAdpter(myJokes);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adpter);
adpter.notifyDataSetChanged();
Log.d("MAIN", "获取数据完成" + myJokes.size());
}
@Override
public void onError(Throwable e) {
Log.d("MAIN", "error" + e.toString());
d.dispose();
}
@Override
public void onComplete() {
Log.d("MAIN", "onComplete");
d.dispose();
}
});
}
该方法是运行在主线程中的,所以再也不需要Handler什么的了,非常方便。
最后再看一下布局文件和效果图吧
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.nanke.joke.MainActivity">
<com.cjj.MaterialRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/refresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_View"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</com.cjj.MaterialRefreshLayout>
</RelativeLayout>
效果图
源码地址:https://github.com/HelloNanKe/Joke
咦,还差一点,包含HTML标签的文本处理
Spanned sp = Html.fromHtml( joke.getContent() );
holder.content.setText(sp);