美文网首页
Jetpack Compose 网络请求

Jetpack Compose 网络请求

作者: 海龙lv | 来源:发表于2021-05-19 13:45 被阅读0次

    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<List<Feed>>
        
        @POST(value = "api-admin/login")
        fun logIn(
            @Query("username") username: String,
            @Query("password") password: String
        ): Call<LogInBackData>
    }
    
    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<Feed>())
        val todoItems: LiveData<List<Feed>> = _todoItems
    
        private var _todoItems1 = MutableLiveData(listOf<LogInBackData>())
        val todoItems1: LiveData<List<LogInBackData>> = _todoItems1
    
        fun getList() {
            Network.service.listRepos().enqueue(object : Callback<List<Feed>> {
    
                override fun onResponse(call: Call<List<Feed>>, response: Response<List<Feed>>) {
                    response.body()?.let { it ->
                        _todoItems.value = it.toMutableList()
                    }
                }
    
                override fun onFailure(call: Call<List<Feed>>, t: Throwable) {
                    t.printStackTrace()
                    println("request wrong")
                }
            })
        }
    
        fun getLog() {
    
            Network.service.logIn(username = "13964299760", password = "z2399395")
                .enqueue(object : Callback<LogInBackData> {
    
                    override fun onResponse(
                        call: Call<LogInBackData>,
                        response: Response<LogInBackData>
                    ) {
                        response.body()?.let { it ->
                            _todoItems1.value = mutableListOf(it)
                            println("logloglog${it}")
                        }
                    }
    
                    override fun onFailure(call: Call<LogInBackData>, t: Throwable) {
                        t.printStackTrace()
                        println("request wrong1:$t")
                    }
                })
        }
    }
    
    

    结合liveData进行实现。

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

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

    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 网络请求

          本文链接:https://www.haomeiwen.com/subject/zmcpjltx.html