Jetpack Compose 网络请求

Jetpack Compose已经出现Beta版本好久了,尝试了一下,总的感觉和Flutter、SwiftUI葫芦画瓢的。同样的响应式、快速搭建UI界面,同时,jetpack compose结合Kotlin的语言特性,必定能给安卓的原生开发重新树立新的标杆。

好了,下面来说说Jetpack Compose的网络请求。废话不多说,上正题:

1.使用框架: Retrofit2

在app的build.gradle内添加如下:

dependencies {

    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
  
}

2.封装Network,代码如下

interface RequestService {
    
    @GET("elephants")
    fun listRepos(): Call>
    
    @POST(value = "api-admin/login")
    fun logIn(
        @Query("username") username: String,
        @Query("password") password: String
    ): Call
}

class Network {
    companion object {
        //创建拦截器
        private val interceptor = Interceptor { chain ->
            val request = chain.request()
            val requestBuilder = request.newBuilder()
            val url = request.url()
            val builder = url.newBuilder()
            requestBuilder.url(builder.build())
                .method(request.method(), request.body())
                .addHeader("clientType", "IOS")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
            chain.proceed(requestBuilder.build())
        }

        //创建OKhttp
        private val client: OkHttpClient.Builder = OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .retryOnConnectionFailure(false)


        private var retrofit: Retrofit = Retrofit.Builder()
            .baseUrl("你的baseUrl")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client.build())
            .build()

        var service: RequestService = retrofit.create(RequestService::class.java)

    }

可以实现请求头的配置、超时时间的配置、以及包括了简单的Get请求和Post请求的案例,用接口进行封装。

3.封装ViewModel类进行对对应接口的调用,代码如下:

class ViewMod : ViewModel() {
    private var _todoItems = MutableLiveData(listOf())
    val todoItems: LiveData> = _todoItems

    private var _todoItems1 = MutableLiveData(listOf())
    val todoItems1: LiveData> = _todoItems1

    fun getList() {
        Network.service.listRepos().enqueue(object : Callback> {

            override fun onResponse(call: Call>, response: Response>) {
                response.body()?.let { it ->
                    _todoItems.value = it.toMutableList()
                }
            }

            override fun onFailure(call: Call>, t: Throwable) {
                t.printStackTrace()
                println("request wrong")
            }
        })
    }

    fun getLog() {

        Network.service.logIn(username = "13964299760", password = "z2399395")
            .enqueue(object : Callback {

                override fun onResponse(
                    call: Call,
                    response: Response
                ) {
                    response.body()?.let { it ->
                        _todoItems1.value = mutableListOf(it)
                        println("logloglog${it}")
                    }
                }

                override fun onFailure(call: Call, t: Throwable) {
                    t.printStackTrace()
                    println("request wrong1:$t")
                }
            })
    }
}

结合liveData进行实现。

4.模型创建,用数据类进行创建,如下:

data class LogInBackData(
    val msg: String,
    val code: Int, 
    val data: Map
    )

5.在Activity里面调用,代码如下:

@Composable
fun CreateItems(viewModel: ViewMod) {
    val mList by viewModel.todoItems.observeAsState()
    viewModel.getList()
    LazyColumn {
        itemsIndexed(items = mList!!) { index, item: Feed ->
           println("网络数据是:${mList}")
            SingleItem(item = item, onClick = {
            })
        }
    }
}

其中的ViewMode是上面定义的继承自ViewModel的实例,结合LiveData的observeAsState保证了数据的刷新。

小结:由于本人是iOS开发,刚转安卓,还请各位大神指教、提点,共同进步

你可能感兴趣的:(Jetpack Compose 网络请求)