Cannot resolve method Observable.from in rxjava 2

白昼怎懂夜的黑 提交于 2019-12-10 12:31:29

问题


There is a from method in the Observable class in rxjava 1 but not found in rxjava 2. How can I replace the from method in rxjava 2 in the following code:

    List<Integer> ints = new ArrayList<>();
    for (int i=1; i<10; i++) {
        ints.add(new Integer(i));
    }
    Observable.just(ints)
            .flatMap(new Function<List<Integer>, Observable<Integer>>() {
                @Override
                public Observable<Integer> apply(List<Integer> ints) {
                    return Observable.from(ints);
                }
            })

回答1:


You can use Observable.fromIterable(source)

From documentation:

Some operator overloads have been renamed with a postfix, such as fromArray, fromIterable etc. The reason for this is that when the library is compiled with Java 8, the javac often can't disambiguate between functional interface types.

List<Integer> ints = new ArrayList<>();
for (int i=1; i<10; i++) {
    ints.add(new Integer(i));
}
Observable.just(ints)
        .flatMap(new Function<List<Integer>, Observable<Integer>>() {
            @Override
            public Observable<Integer> apply(List<Integer> ints) {
                return Observable.fromIterable(ints);
            }
        })



回答2:


You don't need to use .just() because you can create Observable directly from your list via fromIterable() operator.

    Observable.fromIterable(ints)



回答3:


I guess it's a bit late, but I just wanted to let people know, the API changes related to the from operator in the RxJava documentation:

from disambiguated into fromArray, fromIterable, fromFuture




回答4:


If you need a List then you can simply use Java Stream and create a List from it and then pass it directly to the Observable.fromIterable method. Like this:

Observable.fromIterable(IntStream.rangeClosed(lowerLimitInclusive,upperLimitInclusive)
            .boxed()
            .collect(Collectors.toList()));   

Or

Observable.fromIterable(Stream.iterate(lowerLimitInclusive, integer -> integer + 1)
                .filter(integer -> integer < (upperLimit+1))
                .limit((long(upperLimit+1)-long(lowerLimitInclusive))
                .collect(Collectors.toList()));  


来源:https://stackoverflow.com/questions/41605586/cannot-resolve-method-observable-from-in-rxjava-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!