Service methods cannot return void. retrofit

前端 未结 4 1678
执念已碎
执念已碎 2020-12-09 01:30

This is my method in Interface. I am calling this function but app crash with this exception:

Caused by: java.lang.IllegalArgumentException: Service m

相关标签:
4条回答
  • 2020-12-09 02:07

    You can always do:

    @POST("/endpoint")
    Call<Void> postSomething();
    

    EDIT:

    If you are using RxJava, since 1.1.1 you can use Completable class.

    0 讨论(0)
  • 2020-12-09 02:09

    Based on your classes, it looks like you are using Retrofit 2.0.0, which is currently in beta. I think using a void in your service method is no longer allowed. Instead, return Call, which you can enqueue to perform the network call asynchronously.

    Alternatively, drop your library down to Retrofit 1.9.0 and replace your Retrofit class with RestAdapter.

    0 讨论(0)
  • 2020-12-09 02:10

    There is difference in Asynchronous in Retrofit 1.9 and 2.0

    /* Synchronous in Retrofit 1.9 */

    public interface APIService {
    
    @POST("/list")
    Repo loadRepo();
    
    }
    

    /* Asynchronous in Retrofit 1.9 */

    public interface APIService {
    
    @POST("/list")
    void loadRepo(Callback<Repo> cb);
    
    }
    

    But on Retrofit 2.0, it is far more simple since you can declare with only just a single pattern

    /* Retrofit 2.0 */
    
    public interface APIService {
    
    @POST("/list")
    Call<Repo> loadRepo();
    
    }
    

    // Synchronous Call in Retrofit 2.0

    Call<Repo> call = service.loadRepo();
    Repo repo = call.execute();
    

    // Asynchronous Call in Retrofit 2.0

    Call<Repo> call = service.loadRepo();
    call.enqueue(new Callback<Repo>() {
    @Override
    public void onResponse(Response<Repo> response) {
    
       Log.d("CallBack", " response is " + response);
    }
    
    @Override
    public void onFailure(Throwable t) {
    
      Log.d("CallBack", " Throwable is " +t);
    }
    });
    
    0 讨论(0)
  • 2020-12-09 02:19

    https://github.com/square/retrofit/issues/297

    Please go through this link.

    "All interface declarations will be required to return an object through which all interaction will occur. The behavior of this object will be similar to a Future and will be generic typed (T) for the success response type."

    @GET("/foo")
    Call<Foo> getFoo();
    

    Based on the new Retrofit 2.0.0 beta You cannot specify return type as void to make it asynchronous

    as per the code inside retrofit (https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit/MethodHandler.java) it will show exception when you try the previous implementation with 2.0.0 beta

    if (returnType == void.class) {
    throw Utils.methodError(method, "Service methods cannot return void.");
    }
    
    0 讨论(0)
提交回复
热议问题