Android 需要帮助Kotlin合作项目、架构组件和改造

Android 需要帮助Kotlin合作项目、架构组件和改造,android,retrofit,android-architecture-components,android-livedata,retrofit2.6,Android,Retrofit,Android Architecture Components,Android Livedata,Retrofit2.6,我正试图将我的头脑集中在提到的组件上,但我不能正确地理解它。我想做一些非常简单的事情:从网络获取数据并将其呈现给用户。目前我还没有缓存它,因为我还在学习体系结构组件中的新协同程序特性。每次应用加载时,我都会收到一个空模型,这看起来很奇怪 我的API是得到击中罚款和响应是200这是正常的 以下是我的尝试: 波乔 存储库 class UserRepo(val context: Context, val api: Api) { suspend fun getProfile(): Profil

我正试图将我的头脑集中在提到的组件上,但我不能正确地理解它。我想做一些非常简单的事情:从网络获取数据并将其呈现给用户。目前我还没有缓存它,因为我还在学习体系结构组件中的新协同程序特性。每次应用加载时,我都会收到一个空模型,这看起来很奇怪

我的API是得到击中罚款和响应是200这是正常的

以下是我的尝试:

波乔

存储库

class UserRepo(val context: Context, val api: Api) {

    suspend fun getProfile(): Profile
    {
        val accessToken = ....
        return api.getUserProfile(accessToken)

    }
}
原料药

视图模型

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()
val viewModel=ViewModelProviders.of(activity!!).get(UserViewModel::class.java)
viewModel.userProfileData.observe(这个,观察者{
//它具有空值
})
//触发变化
viewModel.getProfile()

所以我添加了HTTP请求和响应(多亏@commonware指出了这一点),碰巧我使用了一种不同于预期的模型。映射JSON响应的正确模型是
ProfileResponse
,正如您在我发布的代码中看到的,我使用了Profile。因此,所有字段都为空,因为Gson无法将JSON正确序列化为
Profile
对象


@commonware在评论中指出了这一点,这一切都归功于@commonware。

“每次加载应用程序时,我都会发布一个空的模型”——这表明改型很难将服务器响应转换为指定对象。您可以考虑添加OKHTTP日志拦截器来查看原始响应的外观,看看它是否符合您的预期。我要补充一点。你发现我当前的代码有什么错误吗?除了我所问的之外,我也将感谢批评。我看到的片段似乎没问题。谢谢检查!我建议在try/catch中包装
userRepo.getProfile()
,然后查看是否捕获到错误。
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()