0

在我的安卓应用中:

应用程序/build.gradle

implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'
implementation "com.squareup.retrofit2:converter-gson:2.6.0"
implementation "com.squareup.retrofit2:retrofit:2.6.0"

在我的界面中:

import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query


interface MyRestClient {

    @GET("/event")
    suspend fun getEvents(@Query("orgn") base: Int, @Query("event") quote: Int): Response<List<Event>>
}

我想同步调用这个方法。

所以我试试这个:

    import retrofit2.Call
    import retrofit2.Response

    class TransportService {
        companion object {
            private val myRestClient =
                RestClientFactory.createRestClient(MyRestClient ::class.java)

            suspend fun getEventSync(orgn: Int, event: Int): Response<*> {
                val call: Call<*> = myRestClient .getEvents(orgn, event)      
                   return call.execute()
                }

并以此调用:

import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

 viewModelScope.launch(Dispatchers.Main) {
            val response = TransportService.getEvents(100, 200)

但我在这一行得到编译错误:

val call: Call<*> = myRestClient.getEvents(orgn, event)   

错误是:

Type mismatch: inferred type is Response<List<Event>> but Call<*> was expected
4

3 回答 3

1

错误消息告诉您问题所在。

val call: Call<*> = myRestClient.getEvents(orgn, event)   

getEvents返回Response<List<Event>>,但您试图将其分配给Call<*>.

使用改造 2.6 和协程,您不再需要调用。

getEventSync功能不再有意义。您可以在调用点决定同步和异步。对于阻塞:

val events: Reponse<List<Event>> = runBlocking {
        myRestClient.getEvents(orgn, event)
}
于 2019-11-09T17:05:17.280 回答
0

这是我的解决方案:

 viewModelScope.launch(Dispatchers.Main) {
            Debug.d(TAG, "step_1")
            TransportService.getEvents(100, 200)
            Debug.d(TAG, "step_2")
            TransportService.getEvents(300, 400)
            Debug.d(TAG, "step_3")
            TransportService.getEvents(500, 600)
            Debug.d(TAG, "step_4")
        }

在 TransportService.kt

suspend fun getEvents(
            orgn: Int,
            event: Int
        ): Response<*> {
            return  waitressCallRestClient.getEvents(orgn, event)
        }

在界面中:

@GET("/event")
    suspend fun getEvents(@Query("orgn") base: Int, @Query("event") quote: Int): Response<List<Event>>

因为我使用改造 2.6并且仅在完成后suspend作为结果step_2打印TransportService.getEvents(100, 200)。而step_2仅在完成后打印 TransportService.getEvents(300, 400),依此类推。

所以这就是我需要的。我有同步调用getEvents()

于 2019-11-09T17:19:42.533 回答
0

Response在界面中返回一个类型MyRestClient,但CallTransportService.

在您的TransportService课程中,将参数类型val call从 from更改Call<*>Response<List<Event>>

此外,由于您希望同步执行此方法,因此您可能不需要方法suspend上的修饰符getEvents

于 2019-11-09T16:58:34.577 回答