android - 需要帮助 Kotlin Coroutines、Architecture Component 和 Retrofit

标签 android retrofit android-architecture-components android-livedata retrofit2.6

我正在努力思考所提到的组件,但我做不对。我想做一些非常简单的事情:从网络中获取数据并将其呈现给用户。目前我还没有缓存它,因为我还在学习架构组件中的新协程特性。每次加载应用程序时,我都会发布一个空模型,这看起来很奇怪。

我的 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)

    }
}

应用程序接口(interface)

interface GatewayApi {
    @GET("users/profile")
    suspend fun getUserProfile(@Query("access-token") accessToken: String?): Profile
}

View 模型

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()
    }
}

最后是我 fragment 的相关代码

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 在评论中指出这一点。

关于android - 需要帮助 Kotlin Coroutines、Architecture Component 和 Retrofit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57402965/

相关文章:

android - 房间查询 : find within list is always returning null

java - SQLite:如何使用单个 SQL 命令创建列和索引

java - 我如何使用改造和recyclerView解析json对象

java - 为什么我不能创建多个 GsonBuilder 并为每个 GsonBuilder 注册不同类型的适配器?

java - Retrofit:如何发送带有常量字段的 POST 请求?

android - 在 AndroidViewModel 中初始化 LiveData

安卓。无法实例化 Worker

android - RecyclerView 是否为空

java - 在为图像集成 firebase 数据引用时,我遇到了下面提到的错误

java - 在 android 中使用复选框在 ListView 中显示 toast 消息