问题
public class RxJavaTest {
public static void main(String[] args) {
Observable.timer(2, TimeUnit.SECONDS).subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Exception {
System.out.println("timer: accept " + aLong);
}
});
}
}
Why is there no information output from the console after two seconds?
回答1:
By default the timer
operator is executed in a different Thread (in the computation thread pool) and your main
thread is exited just after calling the subscribe and shutdowns the VM.
Yo have different solutions for this.
- Add a
Thread.sleep(value > 2000)
after yoursubscribe
- Call
blockingSubscribe
instead ofsubscribe
. The current thread (main) blocks until the upstream terminates - Change the time scheduler to trampoline :
Observable.timer(2, TimeUnit.SECONDS, Schedulers.trampoline())
From the documentation
The default implementation's {@link Scheduler#scheduleDirect(Runnable)} methods execute the tasks on the current thread without any queueing and the timed overloads use blocking sleep as well.
来源:https://stackoverflow.com/questions/59005142/why-is-there-no-information-output-from-the-console-after-two-seconds-rxjava