我正在尝试使用协程将Json解析为MVVM中的Recyclerview来学习MVVM体系结构。但是我在BlogRepository类上遇到错误。
我的Json文件如下所示:
[
{
"id": 1,"name": "potter","img": "https://images.example.com/potter.jpg"
},{ …}
]
我已经创建了如下数据类:
@JsonClass(generateAdapter = true)
class ABCCharacters (
@Json(name = "id") val char_id: Int,@Json(name = "name") val name: String? = null,@Json(name = "img") val img: String
)
然后如下所示的RestApiService:
interface RestApiService {
@GET("/api")
fun getPopularBlog(): Deferred<List<ABCCharacters>>
companion object {
fun createCorService(): RestApiService {
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(1,TimeUnit.MINUTES)
.readTimeout(30,TimeUnit.SECONDS)
.writeTimeout(15,TimeUnit.SECONDS)
.build()
return Retrofit.Builder()
.baseUrl("https://example.com")
.addConverterFactory(moshiConverterFactory.create())
.client(okHttpClient)
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build().create(RestApiService::class.java)
}
}
}
BlogReposity.kt
class BlogRepository() {
private var character = mutableListOf<ABCCharacters>()
private var mutableLiveData = MutableLiveData<List<ABCCharacters>>()
val completableJob = Job()
private val coroutinescope = Coroutinescope(Dispatchers.IO + completableJob)
private val thisApiCorService by lazy {
RestApiService.createCorService()
}
fun getMutableLiveData():MutableLiveData<List<ABCCharacters>> {
coroutinescope.launch {
val request = thisApiCorService.getPopularBlog()
withContext(Dispatchers.Main) {
try {
val response = request.await()
val mBlogWrapper = response;
if (mBlogWrapper != null && mBlogWrapper.name != null) {
character = mBlogWrapper.name as MutableList<ABCCharacters>
mutableLiveData.value=character;
}
} catch (e: HttpException) {
// Log exception //
} catch (e: Throwable) {
// Log error //)
}
}
}
return mutableLiveData;
}
}
最后是ViewModel类
class MainViewModel() : ViewModel() {
val characterRepository= BlogRepository()
val allBlog: LiveData<List<ABCCharacters>> get() = characterRepository.getMutableLiveData()
override fun onCleared() {
super.onCleared()
characterRepository.completableJob.cancel()
}
}
我是根据https://itnext.io/kotlin-wrapping-your-head-around-livedata-mutablelivedata-coroutine-networking-and-viewmodel-b552c3a74eec完成此操作的 有人可以指导我哪里出问题了以及如何解决?