build插件安装

  1. //retrofit网络请求
  2. implementation 'com.squareup.retrofit2:retrofit:2.6.1'
  3. implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
  4. //协程
  5. implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"
  6. implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3"

api.kt

package com.example.sandapp.utils

import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET

object ServiceCreator {

    private const val BASE_URL = "http://10.0.255.200:3000"

    private val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)

    inline fun <reified T> create(): T = create(T::class.java)

}



interface AppService {
    @GET("/api")
    fun getAppData(): Call<List<String>>
}

在viewMode中使用

class UserListMode: ViewModel(){
    private val _userList = MutableLiveData(userListData)
    val userList: MutableLiveData<List<String>> = _userList

    fun getData(){
        Log.i("api", "请求1" )
        val appService = ServiceCreator.create<AppService>()
        viewModelScope.launch {
//            delay(10000)
            appService.getAppData().enqueue(object : Callback<List<String>> {
                override fun onResponse(call: Call<List<String>>, response: Response<List<String>>) {
                    val list = response.body()
                    _userList.value = response.body()
                    Log.i("api", list.toString() )
                }

                override fun onFailure(call: Call<List<String>>, t: Throwable) {
                    t.printStackTrace()
                    Log.i("api", "请求失败 ${t}" )
                }
            })
        }

    }
}