首页 > 解决方案 > Kotlin - 协程请求不会等到第一个请求完成

问题描述

我有 2 个请求:SIGNUPSIGNUP_UPLOAD_AVATAR

@POST(SIGNUP)
fun registerUser(@QueryMap(encoded = true) userCredentials: HashMap<String, Any>): Deferred<Response<UserResponse>>


@Multipart
@POST(SIGNUP_UPLOAD_AVATAR) //SHOULD BE A PUT, DUE TO ONLY SEND FILE.
fun uploadAvatar(@Part file: MultipartBody.Part): Deferred<Response<ResponseBody>>

目前我决定改变使用COROUTINES但是我有一个问题,即当第一个帖子SIGNUP_UPLOAD_AVATAR开始他的请求时,我需要等到它完成才能使用SIGNUP过程。然而,第二个协程立即开始,而不询问第一个请求是否完成或仍在工作。

这是我的功能:

fun getImageUrlCoRoutine(){
        val requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), profilePicture)
        val body = MultipartBody.Part.createFormData("file", "android.${getFileExtension(profilePicture)}", requestFile)

        val service = APIService.create()
        val request = service.uploadAvatar(body)
        try {
            GlobalScope.launch(Dispatchers.Main) {
                val response = CoroutineUtil().retryIO (times = 3){ request.await() }
                val responseCode = StatusCode(response.code()).description
                when(responseCode){
                    StatusCode.Status.OK -> {
                        response.body()?.let {
                            it.let {
                                println("RESULT: " + it.string())
                                avatarUrl = it.string()

                                println("Avatar: " + avatarUrl)
                                registrationCoroutine(this)  <- here goes for the second request(registration)
                            }
                        }
                    }
                    else -> {}
                }
            }
        }catch (e: HttpException){
            val responseCode = StatusCode(e.code()).description
            when(responseCode){
                StatusCode.Status.NotAcceptable -> {
                }
                else -> {
                }
            }
        }catch (e: Throwable){
            println("Houston we got a Coroutine Problem")
            println(e)
        }
    }



fun registrationCoroutine(suspended: CoroutineScope) {
        val service = APIService.create()
        val data = HashMap<String, Any>()
        data["email"] = email
        data["phone"] = phoneNumber
        data["username"] = email
        data["password"] = password
        data["fullName"] = fullname
        data["token"] = ""
        data["appName"] = BuildConfig.APP_NAME
        data["avatarUrl"] = avatarUrl
        data["deviceType"] = BuildConfig.PLATFORM
        data["needsVerify"] = false

            suspended.launch {
                val request = service.registerUser(data)
                try {
                    val response = CoroutineUtil().retryIO(times = 3) { request.await() }
                    val responseCode = StatusCode(response.code()).description
                    when(responseCode){
                        StatusCode.Status.OK -> {
                            response.body()?.let {
                                it.let {
                                    println(it)
                                }
                            }
                        }
                        else -> {}
                    }
                } catch (e: HttpException) {
                    val responseCode = StatusCode(e.code()).description
                    when(responseCode){
                        StatusCode.Status.NotAcceptable -> {}
                        else -> {}
                    }
                } catch (e: Throwable) {
                    println("Houston we have a coroutine problem")
                    println(e)
                }
        }
    }

以及我得到的回应...

2019-06-25 08:41:28.858 19886-19886/com.multirequest.development I/System.out:结果:

2019-06-25 08:41:28.859 19886-19886/com.multirequest.development I/System.out:头像:

2019-06-25 08:41:28.880 19886-20735/com.multirequest.development D/OkHttp: --> POST http://myCustomURL.com/signup?deviceType=ANDROID&password=demdemdem&needsVerify=false&phone=+1123456789&avatarUrl=&appName= DEMO&fullName=demmmm&email=demm@gmail.com&username=demm@gmail.com&token= 201

当我获得 AvatarURL 时,我需要注册过程开始......

谢谢 :)

标签: kotlincoroutinekotlin-coroutines

解决方案


推荐阅读