简体   繁体   English

有人能理解 java.lang.IllegalStateException: Only one Observer allowed in this short example 吗?

[英]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.我意识到 30491785 讨论了这一点,但没有真正解释为什么会产生错误,并且该示例涉及无关代码。 I'd like to ask the question with a 5 line example.'我想用一个 5 行的例子来问这个问题。

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?问题是 gwindows 发生了什么而 swindows 没有发生(除了类型不同的事实),是否有任何解决方法?

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. GroupedObservable 是一种单播类型的源,您不能多次使用它。 The problem is with your code at g.window(g, ...) where the window operator attempts to subscribe twice.问题在于您在 g.window(g, ...) 处的代码,其中窗口运算符尝试订阅两次。 Use publish(Function) to share the single use g:使用 publish(Function) 共享单机使用 g:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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