简体   繁体   中英

Android Retrofit2 generics method

I use Retrofit2 to connect to the server,

To simplify the number of request methods, I use generics. But the problem is that retrofit does not accept the generic method. I put the sample code below. Does anyone know a solution?

Photo 1):

APIInterface

import io.reactivex.Observable
import okhttp3.RequestBody
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path

interface APIInterface {

   @POST("{url}") fun <T> post(
      @Path("url") url: String,
      @Body body: RequestBody
   ): Observable<T>

   @GET("{url}") fun <T> get(
      @Path("url") url: String
   ): Observable<T>
}

Photo 2:

APIService

import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.RequestBody
import java.io.Serializable

class APIService constructor(private val mApi: APIInterface) {

   fun <T: Serializable> post(url: String, body: RequestBody): Observable<T>{
      val observable = mApi.post<T>(url, body)
      observable.subscribeOn(Schedulers.io())
         .observeOn(AndroidSchedulers.mainThread())
      return observable
   }

   fun <T: Serializable> get(url: String): Observable<T> {
      val observable = mApi.get<T>(url)
      observable.subscribeOn(Schedulers.io())
         .observeOn(AndroidSchedulers.mainThread())
      return observable
   }
}

Photo 3:

call in controller

mAPIService.post<SignUpModel>(URL_SIGN_UP, body)
        .subscribe(object : APIObserver<SignUpModel> {
            override fun onNext(it: SignUpModel) {
    .
    .
    .

Photo 4:

crash:(

W: java.lang.IllegalArgumentException: Method return type must not include a type variable or wildcard: io.reactivex.Observable<T>
W: for method APIInterface.post
    .
    .
    .

Type information needs to be fully known at runtime in order for deserialization to work.

You cannot do this,the type info needs to be fully static and not a generic, otherwise retrofit cannot correctly generate the Service. Look at here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM