RxJava1到Rxjava2迁移错误

时间:2017-09-25 11:27:48

标签: android retrofit2 rx-java2 retrolambda

将RxJava1代码转换为RXJava2发出此错误,不确定我做错了什么

没有类型变量R的实例存在,因此Single>符合ObserableSource

API调用

@GET("/search/users?per_page=2")
Observable<UsersList> searchGithubUsers(@Query("q") String searchTerm);

@GET("/users/{username}")
Observable<User> getUser(@Path("username") String username);

RxJAva1:

 public Observable<List<User>> searchUsers(final String searchTerm) {
        return Observable.defer(() -> githubUserRestService.searchGithubUsers(searchTerm).concatMap(
                usersList -> Observable.from(usersList.getItems())
                        .concatMap(user -> githubUserRestService.getUser(user.getLogin())).toList()))
                .retryWhen(observable -> observable.flatMap(o -> {
                    if (o instanceof IOException) {
                        return Observable.just(null);
                    }
                    return Observable.error(o);
                }));
    }

RXJava2

   public Observable<List<User>> searchUsers(final String searchTerm) {
        return Observable.defer(() -> githubUserRestService.searchGithubUsers(searchTerm).concatMap(
                usersList -> Observable.fromIterable(usersList.getItems())
                        .concatMap(user -> githubUserRestService.getUser(user.getLogin())).toList()))
                .retryWhen(observable -> observable.flatMap(o -> {
                    if (o instanceof IOException) {
                        return Observable.just(null);
                    }
                    return Observable.error(o);
                }));
    }

2 个答案:

答案 0 :(得分:2)

toList在2.x中返回Single;你必须在它之后申请toObservable()。另请注意,Observable.just(null)被禁止:RxJava 2通常不允许使用空值。

Observable<List<User>> searchUsers(final String searchTerm) {
    return Observable.defer(() -> 
         githubUserRestService
            .searchGithubUsers(searchTerm)
            .concatMap(usersList -> 
                 Observable.fromIterable(usersList.getItems())
                   .concatMap(user ->
                       githubUserRestService
                       .getUser(user.getLogin()))
                       .toList()
                       .toObservable()
                   )
            )
            .retryWhen(observable -> 
                observable.flatMap(o -> {
                    if (o instanceof IOException) {
                        return Observable.just(0);
                    }
                    return Observable.error(o);
                })
            )
       );
}

答案 1 :(得分:0)

尝试使用RxJava2CallAdapterFactory

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://example.com/")
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .build();