Android RxJava 错误 return 订阅类型

Android RxJava wrong return type for subscription

我刚开始使用 RxJava 和 RxAndroid,并且正在研究 this basic example。我在订阅 Observable 的最后一部分遇到了问题,也就是这段代码。

subscription = GithubClient.getInstance()
            .getStarredRepositories(userName)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<GithubRepo>>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(List<GithubRepo> githubRepos) {
                    githubRepoAdapter.setGithubRepos(githubRepos);
                }
            });

不知道是教程过时了还是我哪里做错了。我认为它可能是我的,因为我的进口是错误的,但我已经尝试了所有这些并且 none 工作。这些是此代码的导入。

import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.Observer;
import rx.Subscription;
import rx.schedulers.Schedulers;

我也试过这些:

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import rx.Subscription;

但是观察者必须实现不同的方法:

    subscription = GithubClient.getInstance()
            .getStarredRepositories(userName)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<GithubRepo>>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(List<GithubRepo> githubRepos) {
                    githubRepoAdapter.setGithubRepos(githubRepos);
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });

使用此代码我得到错误 Required: rx.Subscription, Found: void

相关依赖项:

implementation 'io.reactivex.rxjava2:rxjava:2.2.6'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.5.0'

勾选this一项。这是一个工作项目,但有点复杂。您不需要使用第二个请求,只需使用第一个。

val allRepositories =
    gitHubApi.getAllPublicRepositories().map {
    // taken sublist because GitHub has a restriction up to 60 calls rate limit per hour.
    it.subList(0, 5)
    }.doOnError {
        Log.e(TAG, "Exception: ", it)
    }.subscribeOn(Schedulers.io())

并根据需要进行其他修改。

GitHub has a restriction up to 60 calls rate limit per hour.

也许你应该检查一下 https://api.github.com/rate_limit

当谈到你的例子时link使用的是RxJava-1。但是在你的进口中,RxJava-2 是进口的 =)

第 2 个 RX 订阅方法已更改,现在 returns 无效。

尝试使用 subscribeWith() 而不是 subscribe(),或者将 subscribe() 作为 void 函数调用