如何通过ViewModel从Fragment观察Repository LiveData

时间:2019-10-31 09:12:42

标签: android kotlin android-architecture-components android-livedata kotlin-coroutines

在遇到Repository请求的情况下如何连接ViewModel@GET的实时数据并观察片段中的内容时,我很费力。

当请求类型为@POST时,我没有这个问题,因为我可以在正文上使用Transformation.switchMap,并且只要正文更改存储库的功能就被调用并向响应实时数据发出值像这样

val matchSetsDetail: LiveData<Resource<MatchDetailBean>> = Transformations.switchMap(matchIdLiveData) { matchId ->
        val body = MatchSetRequest(matchId)
        repository.getMatchSet(body)
    }

但是在@GET请求的情况下,我有几个View参数提供的查询参数

我在存储库类中有这个改造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>
}

3 个答案:

答案 0 :(得分:3)

Transformations.switchMap()仅使用MediatorLiveData。由于您的用例有些不同,因此您可以直接自己实现。

class CheckInMapViewModel : ViewModel() {
    private val _checkInResponse = MediatorLiveData<Resource<BaseResponse>>
    val checkInResponse: LiveData<Resource<BaseResponse>> = _checkInResponse

    fun checkInCheckOut(apiKey: String, userId: Int, status: String, latitude: Double, longitude: Double, checkedOn: Long) {
        val data = repository.checkInCheckOutUser(apiKey,userId,status,latitude,longitude,checkedOn)
        _checkInResponse.addSource(data) {
            if (it is Resource.Success || it is Resource.Failure)
                _checkInResponse.removeSource(data)
            _checkInResponse.value = it
        }
    }
}

此代码假定data仅发出一个终端元素Resource.SuccessResource.Failure并用其清除源代码。

答案 1 :(得分:1)

您可以使用中间的LiveData来保存期望的方法,该中间的queryLiveData包含请求参数。调用checkInCheckOut函数时,我们为其设置了一个新值,从而导致checkInResponse发生变化。然后,将使用repository.checkInCheckOutUser将更改转换为switchMap的结果。

CheckInMapViewModel:

class CheckInMapViewModel : ViewModel() {

    private val queryLiveData = MutableLiveData<CheckInCheckOutParam?>()

    init {
        queryLiveData.postValue(null)
    }

    val checkInResponse: LiveData<Resource<BaseResponse>> =
        queryLiveData.switchMap { query ->
            if(query == null) {
                AbsentLiveData.create()
            } else {
                repository.checkInCheckOutUser(
                    query.apiKey,
                    query.userId,
                    query.status,
                    query.latitude,
                    query.longitude,
                    query.checkedOn
                )
            }
        }

    fun checkInCheckOut(
        apiKey: String,
        userId: Int,
        status: String,
        latitude: Double,
        longitude: Double,
        checkedOn: Long
    ) {
        queryLiveData.postValue(
            CheckInCheckOutParam(apiKey, userId, status, latitude, longitude, checkedOn)
        )
    }

    private data class CheckInCheckOutParam(
        val apiKey: String,
        val userId: Int,
        val status: String,
        val latitude: Double,
        val longitude: Double,
        val checkedOn: Long
    )
}

AbsentLiveData:

/**
 * A LiveData class that has `null` value.
 */
class AbsentLiveData<T : Any?> private constructor(resource: Resource<T>) :
    LiveData<Resource<T>>() {

    init {
        // use post instead of set since this can be created on any thread
        postValue(resource)
    }

    companion object {

        fun <T> create(): LiveData<Resource<T>> {
            return AbsentLiveData(Resource.empty())
        }
    }
}

答案 2 :(得分:0)

尝试一下:

class CheckInMapViewModel : ViewModel() {
    private val _checkInResponse: MediatorLiveData<Resource<BaseResponse>> = MediatorLiveData()
    val checkInResponse: LiveData<Resource<BaseResponse>>
    get() = _checkInResponse

    init {
        _checkInResponse.addSource(checkInCheckOut()) {
            _checkInResponse.value = it
        }
    }

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