Android Retrofit2 泛型方法

Android Retrofit2 generics method

我用Retrofit2连接服务器,

为了简化请求方法的数量,我使用了泛型。但问题是retrofit不接受泛型方法。我把示例代码放在下面。有人知道解决方案吗?

照片 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>
}

照片 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
   }
}

照片 3:

call in controller

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

照片 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.

你不能这样做,类型信息需要是完全静态的而不是通用的,否则改造无法正确生成服务。看看here.