【发布时间】:2019-10-31 09:12:42
【问题描述】:
我很难弄清楚如何在@GET 请求的情况下连接我的Repository 和ViewModel 的实时数据并在片段中观察它们。
当请求类型为 @POST 时,我没有这个问题,因为我可以在主体上使用 Transformation.switchMap,并且每当主体更改时,存储库的函数就会被调用并向响应实时数据发出值,类似于这样
val matchSetsDetail: LiveData<Resource<MatchDetailBean>> = Transformations.switchMap(matchIdLiveData) { matchId ->
val body = MatchSetRequest(matchId)
repository.getMatchSet(body)
}
但在@GET 请求的情况下,我的视图提供了几个查询参数
我在存储库类中有这个改造 API 调用,代码如下所示
class Repository {
fun checkInCheckOutUser(apiKey: String, userId: Int, status: String, latitude: Double, longitude: Double, checkedOn: Long): LiveData<Resource<BaseResponse>> = liveData {
emit(Resource.Loading())
try {
val response: Response<BaseResponse> = ApiClient.coachApi.checkInCheckOutUser(apiKey, userId, status, latitude, longitude, checkedOn)
if (response.isSuccessful && response.body() != null) {
if (response.body()!!.isValidKey && response.body()!!.success) {
emit(Resource.Success(response.body()!!))
} else {
emit(Resource.Failure(response.body()!!.message))
}
} else {
emit(Resource.Failure())
}
} catch (e: Exception) {
emit(Resource.Failure())
}
}
}
和ViewModel
class CheckInMapViewModel : ViewModel() {
val checkInResponse: LiveData<Resource<BaseResponse>> = MutableLiveData()
fun checkInCheckOut(apiKey: String, userId: Int, status: String, latitude: Double, longitude: Double, checkedOn: Long): LiveData<Resource<BaseResponse>> {
return repository.checkInCheckOutUser(apiKey,userId,status,latitude,longitude,checkedOn)
}
}
主要问题是我想观察checkInResponse,就像我在@POST请求的情况下观察一样,但不知道如何传递观察存储库LiveData,就像我使用Transformations.switchMap在上面的帖子请求中所做的那样.谁能帮我处理这个案子?
编辑 - 这是我要求的改造服务类
interface CoachApi {
@POST(Urls.CHECK_IN_CHECK_OUT_URL)
suspend fun checkInCheckOutUser(
@Query("apiKey") apiKey: String,
@Query("userId") userId: Int,
@Query("status") status: String,
@Query("latitude") latitude: Double,
@Query("longitude") longitude: Double,
@Query("checkedOn") checkedOn: Long
): Response<SelfCheckResponse>
@POST(Urls.SELF_CHECK_STATUS)
suspend fun getCheckInStatus(
@Query("apiKey") apiKey: String,
@Query("userId") userId: Int
): Response<SelfCheckStatusResponse>
}
【问题讨论】:
-
向我们展示改造 API 接口
-
@coroutineDispatcher 添加。有什么帮助吗?
标签: android kotlin android-architecture-components android-livedata kotlin-coroutines