简体   繁体   中英

Could someone understand the java.lang.IllegalStateException: Only one Observer allowed in this short example?

I realize 30491785 discusses this but there was no real explanation of why the error was generated and the example involved extraneous code. I'd like to ask the question with a 5 line example.'

The question is what is going on with gwindows that is not going on with swindows (other than the fact the types are different) and is there any work-around?

public class OneObservableError {

    public static void main(String[] args) throws Exception {
        Observable<Long> source = Observable.interval(1, TimeUnit.SECONDS);
        Observable<Observable<Long>> swindows = source.window(source, s -> Observable.interval(3, TimeUnit.SECONDS));
        Observable<GroupedObservable<Long, Long>> groups = source.groupBy(x -> x % 4);
        Observable<Observable<Observable<Long>>> gwindows
                = groups.map(g -> g.window(g, i -> Observable.interval(3, TimeUnit.SECONDS)));
        //swindows.flatMap(gw->gw).subscribe(System.out::println); //Works
        gwindows.flatMap(gw -> gw).subscribe(System.out::println); //Fails with Only one Observable allowed     
        sleep(10000);
    }

GroupedObservable is an unicast type of source and you can't use it more than once. The problem is with your code at g.window(g, ...) where the window operator attempts to subscribe twice. Use publish(Function) to share the single use g:

g.publish(gs -> gs.window(gs, ...).flatMap(gw -> gw))...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM