retrofit負責請求網路資料請求,rxjava負責異步執行、thread之間的切換,今天實作基本的rxjava2+retrofit使用方法
首先跟之前android studio 30天學習筆記-介紹retrofit(一)一樣
public interface NextPart {
@GET("todos")
Observable<List<RetrofitSetting>> getCall(); //將原本的call改成Observable
}
public class MainActivity extends AppCompatActivity {
private static final String TAG="Rxjava";
private TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=findViewById(R.id.tv1);//顯示的字
Retrofit retrofit = new retrofit2.Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create()) //Gson解析
.baseUrl("https://jsonplaceholder.typicode.com")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支援RxJava2
.build();
NextPart nextPart= retrofit.create(NextPart.class);
Observable<List<RetrofitSetting>> observable=nextPart.getCall();
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<RetrofitSetting>>() {
@Override
public void onSubscribe(Disposable d) {
Log.d(TAG,"connect");
}
@Override
public void onNext(List<RetrofitSetting> retrofitSettings) {
for (RetrofitSetting retrofitSetting : retrofitSettings) { //retrofitSetting獲得retrofitSettings取回的資料
String content = " ";
content += "userId:" + retrofitSetting.getUserId() + "\n";
content += "id:" + retrofitSetting.getId() + "\n";
content += "title:" + retrofitSetting.getTitle() + "\n";
content += "completed:"+retrofitSetting.getCompleted() +"\n\n";
tv1.append(content);
}
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "fail");
}
@Override
public void onComplete() {
Log.d(TAG,"successful");
}
});
subscribeOn
:設定執行的內容要在哪一個thread執行observeOn
:設定處理回傳的內容在哪一個thread執行
Schedulers.io()
:IO操作的執行緒,常用於網路連線Schedulers.computation()
:CPU計算密集的執行緒,用於處理複雜需要CPU計算的資料Schedulers.newThread()
:創建新的Thread,一般不常用到AndroidSchedulers.mainThread()
:Android主執行緒,用來更新UI
這樣就可以取到值了