我正在尝试编写我的网络请求,以使用改版2.6.0和coroutines暂停乐趣。但我总是得到空对象。这是我第一次尝试改装2.6和coroutines
这是我的示例代码
数据类
data class ProjectList (val data: List<Project>)
示例JSON对象
{
"data": [
{
"project_id": "10824",
"project_name": "Bendor Project",
"project_number": "P010824",
"content_items": [
{
"content_id": "235",
"content_name": "Longonot Project",
"content_description": "Valves Example ",
"content_date_updated": "2019-08-31 12:29:00",
"project_id": "10824",
"media_items": []
网络接口
suspend fun getProjects(@Query("mode") mode: String): ProjectList
改装客户端
class RetrofitClient{
private val gson = GsonBuilder()
.setLenient()
.create()
private fun retrofit(): Retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
val retrofitService: ProjectAPI by lazy {
retrofit().create(ProjectAPI::class.java)
}
存储库
class ProjectRepository {
private val client: ProjectAPI = RetrofitClient().retrofitService
suspend fun getProjectData(mode : String) : ProjectList = client.getProjects(mode)
}
ViewModel中的livedata
val request : LiveData<ProjectList> = liveData(Dispatchers.IO){
val response = repository.getProjectData(SOURCE_MODE)
Log.e(TAG, "${response.data}")
emit(response)
}
我一直得到空响应。我哪里做得不对?
您不需要发出值,只需在协同作用域中调用挂起函数
,然后在ViewModel
中创建一个新的LiveData
,最后调用LiveData.post()以便能够将网络请求的响应分配给LiveData
对象。