简体   繁体   English

Android Retrofit2 generics方法

[英]Android Retrofit2 generics method

I use Retrofit2 to connect to the server,我使用 Retrofit2 连接到服务器,

To simplify the number of request methods, I use generics.为了简化请求方法的数量,我使用 generics。 But the problem is that retrofit does not accept the generic method.但问题是 retrofit 不接受泛型方法。 I put the sample code below.我把示例代码放在下面。 Does anyone know a solution?有谁知道解决方案?

Photo 1):照片1):

APIInterface API接口

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:照片2:

APIService API服务

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:照片3:

call in controller致电 controller

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

Photo 4:照片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.您不能这样做,类型信息需要完全是 static 而不是泛型,否则 retrofit 无法正确生成服务。 Look at here .这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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