1

将 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);
                }));
    }
4

2 回答 2

2

toList returns Single in 2.x; you have to apply toObservable() after it. Note also that Observable.just(null) is forbidden: nulls are generally not allowed with 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);
                })
            )
       );
}
于 2017-09-25T12:21:12.823 回答
0

尝试使用RxJava2CallAdapterFactory

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://example.com/")
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .build();
于 2017-09-25T11:30:52.483 回答