亲宝软件园·资讯

展开

RxJava Retrofit 网络请求 RxJava+Retrofit实现网络请求封装的方法

程序园中猿 人气:0

简要介绍

Retrofit是当前应用非常广泛的网络请求框架,通常结合RxJava来进行网络请求,本文将展示一个采用RxJava+Retrofit的网络请求demo.

集成步骤

1、app工程的build.gradle中添加依赖

//retrofit2
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.2'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'

//rxjava2
implementation 'io.reactivex.rxjava2:rxjava:2.2.2'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'

//配合Rxjava2 使用
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

2、在AndroidManifest.xml中添加权限

<uses-permission android:name="android.permission.INTERNET"/>

3、添加数据类Task

data class Task(var id: Int, var name: String?)

4、 添加网络请求类NetworkService

import io.reactivex.Observable;
import retrofit2.http.GET;
public interface NetworkService {

  @GET("data.json")
  Observable<Task> query();
}

5、activity中调用

class MainActivity : AppCompatActivity() {
  private val BASE_URL = "https://raw.githubusercontent.com/cxyzy1/rxjava_retrofit_demo/master/"

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    queryData()
  }

  private fun queryData() {
    //创建Retrofit对象
    val retrofit = Retrofit.Builder().baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build()

    //获取UserMsgService对象
    val networkService = retrofit.create(NetworkService::class.java)

    networkService.query()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object : Observer<Task> {
          override fun onSubscribe(d: Disposable) {
          }

          override fun onNext(task: Task) {
            contentTv.text = task.toString()
          }

          override fun onError(e: Throwable) {
            Log.v("", e.message)
          }

          override fun onComplete() {
          }
        })
  }
}

网络请求结果截图

 

Demo源代码

https://github.com/cxyzy1/rxjava_retrofit_demo

加载全部内容

相关教程
猜你喜欢
用户评论