需要帮助 Kotlin Coroutines、Architecture Component 和 Retrofit
Need help Kotlin Coroutines, Architecture Component and Retrofit
我正在努力思考所提到的组件,但我无法正确理解。我想做一些非常简单的事情:从网络中获取数据并将其呈现给用户。目前我还没有缓存它,因为我还在学习架构组件中的新协程特性。每次加载应用程序时,我都会发布一个空模型,这看起来很奇怪。
我的 API 被击中了,响应是 200,没问题。
以下是我尝试过的:
POJO
data class Profile(@SerializedName("fullname") val fullName : String.....)
存储库
class UserRepo(val context: Context, val api: Api) {
suspend fun getProfile(): Profile
{
val accessToken = ....
return api.getUserProfile(accessToken)
}
}
API
interface GatewayApi {
@GET("users/profile")
suspend fun getUserProfile(@Query("access-token") accessToken: String?): Profile
}
视图模型
class UserViewModel(application: Application) : AndroidViewModel(application) {
private val usersRepo = UserRepo(application.applicationContext, Apifactory.Api)
val userProfileData = liveData{
emit(usersRepo.getProfile())
}
fun getProfile() = viewModelScope.launch {
usersRepo.getProfile()
}
}
最后是我片段的相关代码
val viewModel = ViewModelProviders.of(activity!!).get(UserViewModel::class.java)
viewModel.userProfileData.observe(this, Observer<UserProfile> {
//it is having nulls
})
//trigger change
viewModel.getProfile()
所以我添加了 HTTP 请求和响应(感谢@CommonsWare 指出这一点),碰巧我使用了与我应该使用的不同的模型。映射 JSON 响应的正确模型是 ProfileResponse
,正如您在我发布的代码中看到的那样,我改用了 Profile。所以所有字段都是空的,因为 Gson 无法正确地将 JSON 序列化为 Profile
对象。
感谢@CommonsWare 在评论中指出这一点。
我正在努力思考所提到的组件,但我无法正确理解。我想做一些非常简单的事情:从网络中获取数据并将其呈现给用户。目前我还没有缓存它,因为我还在学习架构组件中的新协程特性。每次加载应用程序时,我都会发布一个空模型,这看起来很奇怪。
我的 API 被击中了,响应是 200,没问题。
以下是我尝试过的:
POJO
data class Profile(@SerializedName("fullname") val fullName : String.....)
存储库
class UserRepo(val context: Context, val api: Api) {
suspend fun getProfile(): Profile
{
val accessToken = ....
return api.getUserProfile(accessToken)
}
}
API
interface GatewayApi {
@GET("users/profile")
suspend fun getUserProfile(@Query("access-token") accessToken: String?): Profile
}
视图模型
class UserViewModel(application: Application) : AndroidViewModel(application) {
private val usersRepo = UserRepo(application.applicationContext, Apifactory.Api)
val userProfileData = liveData{
emit(usersRepo.getProfile())
}
fun getProfile() = viewModelScope.launch {
usersRepo.getProfile()
}
}
最后是我片段的相关代码
val viewModel = ViewModelProviders.of(activity!!).get(UserViewModel::class.java)
viewModel.userProfileData.observe(this, Observer<UserProfile> {
//it is having nulls
})
//trigger change
viewModel.getProfile()
所以我添加了 HTTP 请求和响应(感谢@CommonsWare 指出这一点),碰巧我使用了与我应该使用的不同的模型。映射 JSON 响应的正确模型是 ProfileResponse
,正如您在我发布的代码中看到的那样,我改用了 Profile。所以所有字段都是空的,因为 Gson 无法正确地将 JSON 序列化为 Profile
对象。
感谢@CommonsWare 在评论中指出这一点。