我正试图围绕上述组件展开思考,但我无法做到正确。我想做一些非常简单的事情:从网络中获取数据并将其呈现给用户。目前还没有缓存它,因为我还在学习架构组件中的新协程特性。每次加载应用程序时,我都会发布一个空模型,这看起来很奇怪。
我的 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()