5

I've an Observable that returns a single Cursor instance (Observable<Cursor>). I'm trying to utilize ContentObservable.fromCursor to obtain every cursor's row in onNext callback.

One of the solutions I've figured out is such construction:

ContentObservable.fromCursor(cursorObservable.toBlocking().first())
    .subscribe(cursor -> {
        // map to object 
        // add to outer collection
    }, e -> {}, () -> { 
        // do something with list of objects (outer collection)
    });

This looks rather like a hack because of toBlocking().first(), but it works. I don't like it because most of the processing is done in onNext callback and we've to create outer collection to hold the intermediate results.

I wanted to use it like this:

cursorObservable.map(ContentObservable::fromCursor)
    .map(fromCursor -> fromCursor.toBlocking().first())
    .map(/* map to object */)
    .toList()
    .subscribe(objects -> {
        // do something with list of objects
    }

This still utilizes toBlocking().first() and doesn't work because once the fromCursor observable has finished the cursor is closed so there's no way to map it to object. Is there a better way to flatten Observable<Observable<Cursor>> to Observable<Cursor>?

4

1 回答 1

12

有没有更好的方法来扁平Observable<Observable<Cursor>>Observable<Cursor>

是的,您可以使用Observable.concat以下方法:

public static void main(String[] args) {
    final Observable<String> observable = Observable.just("1", "2");
    final Observable<Observable<String>> nested = observable.map(value -> Observable.just(value + "1", value + "2"));
    final Observable<String> flattened = Observable.concat(nested);

    flattened.subscribe(System.out::println);
}

更新

实际上还有一些其他方法可以将 an 转换Observable<Observable<Cursor>>Observable<Cursor>

只需选择一个更适合您的。

更新 2

另一种解决方案是稍微修改您的代码并使用flatMap运算符而不是map

cursorObservable.flatMap(ContentObservable::fromCursor)
    .map(/* map to object */)
    .toList()
    .subscribe(objects -> {
        // do something with list of objects (outer collection)
    }
于 2015-05-06T11:52:16.253 回答