Android-将RxJava与翻新配合使用会导致IllegalArgumentException

时间:2019-03-13 18:12:57

标签: java android retrofit2 rx-java2

我试图将RxJava与Retrofit一起使用来链接Android中的网络请求。但是正如我在标题中所述,它会导致IllegalArgumentException。在下面的内容中,您可以看到我到目前为止编写的代码(我还包括导入和gradle文件以及用于我的项目的依赖项):

ApiClient.java:

import retrofit2.Retrofit;

import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Path;
import rx.Observable;


public class ApiClient {

    // trailing slash is needed
    public static final String BASE_URL = "....";

    private static CliqueDBApiInterface sCliqueDBApiInterface;

    public static CliqueDBApiInterface getCliqueDBApiInterface(){

        if(sCliqueDBApiInterface == null){
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();

            sCliqueDBApiInterface = retrofit.create(CliqueDBApiInterface.class);
        }

        return sCliqueDBApiInterface;
    }

    public interface CliqueDBApiInterface{
        @GET("statementsOfClique/{idOfClique}")
        //Call<ListOfStatements> getStatementsOfTheClique(@Path("idOfClique") int id, @Header("Authorization") String authHeader );
        Observable<ListOfStatements> getStatementsOfTheClique(@Path("idOfClique") int id, @Header("Authorization") String authHeader );
    }

}

MainActivity.java:

import retrofit2.HttpException;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

// ... some other code

Observable<ListOfStatements> call = service.getStatementsOfTheClique(clique.getId(), authenticationToken);

call.subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Subscriber<ListOfStatements>() {
          @Override
          public void onNext(ListOfStatements listOfStatements) {
              // Called once the `ListOfStatements` object is available
              List<Statement> statementList = listOfStatements.getStatementsOfClique();
              // do something with statementList


          }

          @Override
          public void onCompleted() {
             // Nothing to do here
          }

          @Override
          public void onError(Throwable e) {
             if (e instanceof HttpException) {
                int code = ((HttpException) e).code();
             }

          }
});

现在gradle文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.celik.abdullah.hefuxi11"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions{
        exclude 'META-INF/rxjava.properties'
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.android.support:cardview-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
    implementation 'io.reactivex:rxandroid:1.2.0'
    implementation 'io.reactivex:rxjava:1.1.4'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'

}

但是应用程序崩溃了,我在LogCat中收到以下错误/异常:

  

03-13 18:36:29.190 4128-4128 / com.celik.abdullah.hefuxi11   E / AndroidRuntime:致命异常:main       流程:com.celik.abdullah.hefuxi11,PID:4128       java.lang.IllegalArgumentException:无法为rx.Observable创建调用适配器           用于方法CliqueDBApiInterface.getStatementsOfTheClique           在retrofit2.Utils.methodError(Utils.java:52)           在retrofit2.HttpServiceMethod.createCallAdapter(HttpServiceMethod.java:60)           在retrofit2.HttpServiceMethod.parseAnnotations(HttpServiceMethod.java:34)           在retrofit2.ServiceMethod.parseAnnotations(ServiceMethod.java:36)           在retrofit2.Retrofit.loadServiceMethod(Retrofit.java:168)           在retrofit2.Retrofit $ 1.invoke(Retrofit.java:147)           在java.lang.reflect.Proxy.invoke(Proxy.java:913)           位于$ Proxy1.getStatementsOfTheClique(未知来源)           在com.celik.abdullah.hefuxi11.adapters.CliqueAdapter $ 1.run(CliqueAdapter.java:124)           在android.os.Handler.handleCallback(Handler.java:790)           在android.os.Handler.dispatchMessage(Handler.java:99)           在android.os.Looper.loop(Looper.java:164)           在android.app.ActivityThread.main(ActivityThread.java:6494)           在java.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:438)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)        原因:java.lang.IllegalArgumentException:无法找到以下对象的调用适配器   rx。可观察。         尝试过:          * retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory          * retrofit2.CompletableFutureCallAdapterFactory          * retrofit2.ExecutorCallAdapterFactory           在retrofit2.Retrofit.nextCallAdapter(Retrofit.java:239)           在retrofit2.Retrofit.callAdapter(Retrofit.java:203)           在retrofit2.HttpServiceMethod.createCallAdapter(HttpServiceMethod.java:58)             ...另外14个

有人知道如何解决该问题吗?我发现了有关此异常的其他一些SO问题,并通过播放/更改gradle文件中的导入包尝试了所有答案,但没有任何效果。构建改造实例时,我还添加了 addCallAdapterFactory(RxJava2CallAdapterFactory.create()),但出现了相同的错误。

谢谢,

3 个答案:

答案 0 :(得分:2)

您正在使用RxJava 1.x的observable和订户。您已在.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

添加了RxJava 2.x的适配器工厂。

您应该从RxJava 2.x导入

因此,您还需要更新依赖项

implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.6'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'




import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;

答案 1 :(得分:2)

是的,要么将所有内容都更新到RxJava2,要么可以使用RxJava1

在这种情况下,您的导入将类似于:

/* rx */
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'io.reactivex:rxjava:1.3.2'

/* retrofit, gson */
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.8.1'
implementation 'com.squareup.retrofit2:converter-scalars:2.4.0'

然后您的RetrofitApiInterface将如下所示:

public static CliqueDBApiInterface getCliqueDBApiInterface(){

    if(sCliqueDBApiInterface == null){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();

        sCliqueDBApiInterface = retrofit.create(CliqueDBApiInterface.class);
    }

    return sCliqueDBApiInterface;
}


where okHttpClient = new OkHttpClient.Builder().build();

答案 2 :(得分:0)

要立即创建一个呼叫,请使用flatMap operator而不是在Subscriber方法中创建subscribe()