Dans mon application Android:
app / build.gradle
Type mismatch: inferred type is Response<List<Event>> but Call<*> was expected
Dans mon interface:
val call: Call<*> = myRestClient.getEvents(orgn, event)
Et je veux appeler cette méthode de manière synchrone
Alors j'essaye ceci:
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)
Et j'appelle par ceci: p>
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()
}
Mais j'obtiens une erreur de compilation dans cette ligne:
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>>
}
l'erreur est:
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"
3 Réponses :
Vous renvoyez un type de Réponse dans votre interface MyRestClient , mais vous attendez un Appel dans votre TransportService .
Dans votre classe TransportService , modifiez le type de paramètre de val call de Call<*> à Response . >
De plus, puisque vous souhaitez exécuter cette méthode de manière synchrone, vous n'avez probablement pas besoin du modificateur suspend sur votre méthode getEvents .
Le message d'erreur vous indique le problème.
val events: Reponse<List<Event>> = runBlocking {
myRestClient.getEvents(orgn, event)
}
J'ai ajouté ma réponse
Voici ma solution:
@GET("/event")
suspend fun getEvents(@Query("orgn") base: Int, @Query("event") quote: Int): Response<List<Event>>
dans TransportService.kt
suspend fun getEvents(
orgn: Int,
event: Int
): Response<*> {
return waitressCallRestClient.getEvents(orgn, event)
}
Dans l'interface:
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")
}