我有2个API,第二个API取决于第一个API的结果。下面是ViewModel中的代码。
fun coroutineDocs(jobRequest: JobRequest) {
viewModelScope.launch {
_mResult.postValue(Resource.loading())
withContext(Dispatchers.IO) {
try {
coroutineScope {
val manifest = async {
manifestRepository.coroutineSendDocs(jobRequest)
}
val manifestResult = manifest.await()
val images = async {
manifestRepository.coroutineUploadAttachment(
userId,manifestResult.responseData?.transactionId
)
}
val imageResult = images.await()
_mResult.postValue(imageResult)
}
} catch (e: Exception) {
_mResult.postValue(Resource.exception(e))
}
}
}
}
我的网络解析代码如下:
data class Resource<out T>(
val status: Status,
val responseData: T? = null,
val headers: Headers?=null,
val errorData: ResponseBody? = null,
val responseCode: Int? = null,
val exception: Exception? = null) {
companion object {
fun <T> success(data: T?, header: Headers): Resource<T> =
Resource(Status.SUCCESS, data,header)
fun <T> error(responseCode: Int?, errorData: ResponseBody?): Resource<T> =
Resource(Status.ERROR, errorData = errorData, responseCode = responseCode)
fun <T> exception(exception: Exception?): Resource<T> =
Resource(Status.EXCEPTION, exception = exception)
fun <T> loading(): Resource<T> =
Resource(Status.LOADING)
}
}
现在,我正在尝试将上述网络解析转换为如下所示的密封类:
sealed class Resource1<out T>{
class Loading<T> : Resource1<T>()
data class Success<T>(val data:T?,val header:Headers) : Resource1<T>()
data class Error<T>(val responseCode: Int?,val errorData: ResponseBody?) : Resource1<T>()
data class Failure<T>(val exception: Exception?):Resource1<T>()
companion object {
fun <T> loading() = Loading<T>()
fun <T> success(data: T?, header: Headers) = Success(data,header)
fun <T> error(responseCode: Int?, errorData: ResponseBody?) =
Error<T>(responseCode, errorData)
fun <T> failure(exception: Exception?) = Failure<T>(exception)
}
}
由于我要更新为密封类,因此需要使用kotlin when()。
如何不使用kotlin when()直接获取值manifestResult.responseData?.transactionId
?
预先感谢