sajad sajad - 4 years ago 115
Java Question

Rxjava schedule wont run after last line

I'm new to RX and i don't know how the schedulers work. below is some code that never run

onComplete
. but if i put a
while(true)
loop at the end it works correctly. it seams the app will exit before running
new thread
.

why is this happening? and how to fix this issue?

Subscriber<String> subscriber = new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println("done");
}

@Override
public void onError(Throwable throwable) {

}

@Override
public void onNext(String o) {
System.out.println(o);
}
};

Observable.from(new String[]{"1", "2", "3","4"}).
subscribeOn(Schedulers.immediate())
.observeOn(Schedulers.newThread())
.subscribe(subscriber);

Answer Source

Just add Thread.sleep(1000); as the last statement if your program exits too early.

As to why this happens.

This answer quotes:

The Java Virtual Machine continues to execute threads until either of the following occurs:

...

All threads that are not daemon threads have died ...

Now if we look at RxThreadFactory that produces threads for Schedulers:

public final class RxThreadFactory extends AtomicLong implements ThreadFactory {

    ...

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r, prefix + incrementAndGet());
        t.setDaemon(true);
        return t;
    }
}

So a more complex solution would be to use Schedulers.from() and pass in a custom Executor with your own ThreadFactory that produces non-daemon threads.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download