我需要将第一个POST
请求发送到服务器,将接收到的响应插入到第二个POST
请求中,然后将其发送回服务器。如何使用RxJava
来实现呢?目前,一切正常,但是第二个问题没有时间从第一个请求中得到答案,并且imageMediaId
字段被发送为空。
我的功能:
fun uploadNewImageAndContact(toPath: String?, newContactApi: ContactsApi) {
val file = File(toPath)
val fileReqBody: RequestBody = file.asRequestBody("image/*".toMediaTypeOrNull())
val part: MultipartBody.Part =
MultipartBody.Part.createFormData("upload", file.name, fileReqBody)
// First Request
imagesService.postImage(part).enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (response.code() == 201) {
// Get Image response Id
val gson = Gson()
val imageResponse =
gson.fromJson(response.body()?.string(), ImageResponse::class.java)
imageMediaId = imageResponse.ids[0]
// Second Request
contactsService.postNewContact(newContactApi)
.enqueue(object : Callback<ContactsApi> {
override fun onFailure(call: Call<ContactsApi>, t: Throwable) {
}
override fun onResponse(call: Call<ContactsApi>, response: Response<ContactsApi>) {
}
})
}
}
})
}
我的ViewModel函数:
val newContactsApi = ContactsApi(id = "", firstName = mFirstName, lastName = mLastName, phone = mPhone,
email = mEmail, notes = mNotes, images = "https://mydb.site.io/media/${apiRepository.imageMediaId}")
apiRepository.uploadNewImageAndContact(toPath, newContactsApi)