RxJava simple demo not work

时间:2017-10-30 15:32:22

标签: rx-java

I just learned RxJava and find it's very useful,but when i start to test some code myself, I find it not work correctly.

I write some code like this,but it's do not print anything.The program stop immediately after the start.

public static void main(String[] args) {
        Observable.just(1, 2, 3, 4)
        .subscribeOn(Schedulers.newThread()) 
        .observeOn(Schedulers.newThread()) 
        .subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer number) {
              System.out.println(number);
            }
        });
    }

and i also find it's only work in main thread. This code will print number

public static void main(String[] args) {
        Observable.just(1, 2, 3, 4)
        .subscribeOn(Schedulers.immediate()) 
        .observeOn(Schedulers.immediate()) 
        .subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer number) {
              System.out.println(number);
            }
        });
    }

I'm using rxjava 1.3.0 and i write this code follow the instruction from a article.

Did i missing something?

(I understand it now,it's looks like the rxjava will not create new thread immediately,so before rxjava can create new thread the main thread will be exited,and the jvm will be shutdown.

To make previous example work,just make main thread live longer.

Observable.just(1, 2, 3, 4)
        .subscribeOn(Schedulers.newThread()) // 
        .observeOn(Schedulers.newThread()) // 
        .subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer number) {
              System.out.println(number);
            }
        });


        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

)

1 个答案:

答案 0 :(得分:0)

使用Observable.toBlocking().subscribe()代替Observable.subscribe()

订阅Observable主线程退出后。虽然rx worker theread默认是deamon线程,但JVM将退出。所以你需要做的是让主线程等待Subscription完成。