添加coil库,在MainActivity中加载图片,简单好用
然后我是想通过viewModel来更新图片的,但没法在viewModel中使用load(),请教正确的用法
MainViewModel.kt
package com.example.retrofittest
import android.content.res.Resources
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.switchMap
class MainViewModel : ViewModel() {
val imageId: LiveData<Resources>
get() = _imageId
private val _imageId = MutableLiveData<Resources>()
// load()爆红了
init {
_imageId.value = load("http://pic-bucket.ws.126.net/photo/0010/2022-11-22/HMP3UMG2POUR0010NOS.png")
}
}
如果没法像MainActivity中那样使用load()的话,那只能改用retrofit访问使用了.但是我在viewModel中不知道该怎么写具体的代码.
图片的数据模型 ImageResponse.kt, image: Resources用这个参数对了吗?
package com.example.retrofittest
import android.content.res.Resources
data class ImageResponse(val image: Resources)
访问接口 ImageService.kt
package com.example.retrofittest
import retrofit2.Call
import retrofit2.http.GET
interface ImageService {
@GET("photo/0010/2022-11-22/HMP3UMG2POUR0010NOS.png")
fun getImageData(): Call<ImageResponse>
}
retrofit构建器 ServiceCreator.kt
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ServiceCreator {
private const val BASE_URL = "http://pic-bucket.ws.126.net/"
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)
}
统一网络数据访问入口 AppNetwork.kt
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
object AppNetwork {
private val imageService = ServiceCreator.create<ImageService>()
suspend fun imageApp() = imageService.getImageData().await()
private suspend fun <T> Call<T>.await(): T {
return suspendCoroutine { continuation ->
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
val body = response.body()
if (body != null) continuation.resume(body)
else continuation.resumeWithException(
RuntimeException("response body is null")
)
}
override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
}
仓库层的统一封装入口
import androidx.lifecycle.liveData
import kotlinx.coroutines.Dispatchers
// 定义仓库层的统一封装入口 Repository.kt
object Repository {
fun imageApp() = liveData(Dispatchers.IO) {
val result = try {
val imagerResponse = AppNetwork.imageApp()
val images = imagerResponse.image
Result.success(images)
} catch (e: Exception) {
Result.failure<ImageResponse>(e)
}
emit(result)
}
}