Приостановить в сопрограмме в Kotlin не ждет ответа от http запроса - PullRequest
0 голосов
/ 19 марта 2020

Мне нужно дождаться ответа http, чтобы я мог поместить его в свое текстовое представление, вот как я это делаю:

LoginFragment

view.next_button.setOnClickListener {
            if (!isTextFieldCorrect(password_edit_text.text!!)) {
                password_text_input.error = getString(R.string.shr_error_password)
                username_text_input.error = getString(R.string.shr_error_username)
            } else {
                next_button.isEnabled = false
                password_text_input.error = null
                username_text_input.error = null
                val model = LoginModel(username_edit_text.text.toString().take(5), password_edit_text.text.toString().take(5))
                apiService = api_service()

                CoroutineScope(IO).launch {
                    var result: String? = apiService!!.login(model)
                    setTextOnMainThread(result.toString())
                }
            }

private fun setTextViewText(input: String) {
        val newText = input
        textView_status.text = newText
    }
    suspend fun setTextOnMainThread(input: String) {
        withContext(Main) {
            setTextViewText(input)
        }
    }

apiService

class api_service {

    var jsonPlaceholderApi: JsonPlaceholderApi? = null

    constructor() {
        var retrofit = Retrofit.Builder()
                .baseUrl("http://192.168.1.8:5000/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        jsonPlaceholderApi = retrofit.create(JsonPlaceholderApi::class.java)
    }

     suspend fun login(model: LoginModel): String? {
        var call: Call<ResponseBody> = jsonPlaceholderApi!!.login(model)
        var responseFromApi: String? = null
        if (!call.isExecuted) {
            call.enqueue(object: Callback<ResponseBody> {
                override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                    responseFromApi = t.message
                    println("RESPONSE ${t.message}")
                }

                override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                    if(response.isSuccessful) {
                        val token = response.body()!!.string()
                        var tokenArr = token.split(':')
                        responseFromApi = tokenArr[1]

                    }
                }
            })
        }

        return responseFromApi
    }
}

jsonPlaceholderApi

interface JsonPlaceholderApi {
    @POST("auth/login")
    fun login(@Body model: LoginModel): Call<ResponseBody>
}

Я не получаю никакой ошибки и при использовании отладки он проходит через setTextOnMainThread(input: String), но в этом нет никакой ценности. Похоже, что доходит до этой части, прежде чем веб-интерфейс дает ответ. Пожалуйста, помогите мне с этим. Спасибо.

...