我有下面的代码,我想询问这个视图模型是否正确或者我是否遗漏了任何东西。我的目标是一个视图模型,它存储 HTTP 请求数据并使用自定义标头发出 HTTP 请求。
我在处理数据类数组时也遇到了麻烦,因为视图模型的第二行有错误。我还希望能够从下面的视图模型中的另一个视图模型获取和设置数据(我尝试实现视图模型的第一行,但它不起作用)。
接口:
interface ApiInterface {
@GET("/data")
suspend fun loadData(authKey: String): Response<ArrayOfDataClassExample>
}
改造实例:
object RetrofitInstance {
private val client = OkHttpClient.Builder().apply {
addInterceptor(Interceptor())
}.build()
val api : ApiInterface by lazy {
Retrofit.Builder()
.baseUrl(Util.Base)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiInterface::class.java)
}
}
数据类:
data class DataClassExample (
val id: Int,
val accountID: Int
)
data class ArrayOfDataClassExample (
val data: Array<DataClassExample>
)
查看型号:
class ServerDataViewModel(application: Application) : AndroidViewModel(application) {
val accountType by preferencesViewModel.accountType.observeAsState("")
var data: ArrayOfDataClassExample = ArrayOfDataClassExample(arrayOf(DataClassExample))
@OptIn(DelicateCoroutinesApi::class)
suspend fun getData() {
GlobalScope.launch(Dispatchers.IO) {
val response = try {
RetrofitInstance.api.loadEntries(authKey = "")
} catch (e: HttpException) {
print(e.message)
return@launch
} catch (e: IOException) {
print(e.message)
return@launch
}
if (response.isSuccessful && response.body() != null) {
withContext(Dispatchers.Main) {
data = response.body()!!
}
}
}
}
}
试试这个
class ServerDataViewModel(application: Application) : AndroidViewModel(application) {
private val _data = MutableLiveData<ArrayOfDataClassExample>()
val data: LiveData<ArrayOfDataClassExample> = _data
fun getData(authKey: String) {
viewModelScope.launch(Dispatchers.IO) {
try {
val response = RetrofitInstance.api.loadData(authKey)
if (response.isSuccessful && response.body() != null) {
_data.postValue(response.body())
} else {
}
} catch (e: HttpException) {
} catch (e: IOException) {
}
}
}
}
和
object RetrofitInstance {
private val client = OkHttpClient.Builder().apply {
addInterceptor { chain ->
val newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer your_auth_key_here")
.build()
chain.proceed(newRequest)
}
}.build()
val api: ApiInterface by lazy {
Retrofit.Builder()
.baseUrl(Util.Base)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiInterface::class.java)
}
}