0

I am not getting TimeoutException if I don't enter any text within 5 seconds. The below code method will call getMsg() and wait for text input. I added 'timeout( 5, TimeUnit.SECONDS )' to wait only for 5 secs for the input. I want to show timeout error in case user did not enter msg with in 5 seconds.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

import rx.Observable;

public class TestRx {

   public static void main( String[] args ) throws IOException {
      Observable.just( getMsg() )
            .timeout( 5, TimeUnit.SECONDS )
            .subscribe( System.out::println,
                  e -> e.printStackTrace() );
      System.out.println( "End..." );
   }

   private static String getMsg() throws IOException {
      BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
      System.out.print( "Enter a msg:" );
      String msg = reader.readLine();
      return msg;
   }
}

1 Answer 1

5

getMsg() executes way before you get into RxJava. just() doesn't magically make the code in its parenthesis happen in a deferred manner. You need fromCallable:

public static void main( String[] args ) {
    Observable.fromCallable(() -> getMsg() )
        .timeout( 5, TimeUnit.SECONDS )
        .subscribe( System.out::println,
              e -> e.printStackTrace() );
    System.out.println( "End..." );
}

Update

The blocking happens on the main thread which is not interrupted in this setup. The alternative is to use subscribeOn and possible blockingSubscribe to wait for the data or termination:

Observable.fromCallable( () -> getMsg() )
          .subscribeOn(Schedulers.io())             // <----------------------
          .timeout( 5, TimeUnit.SECONDS )
          .blockingSubscribe( System.out::println,
                    e -> e.printStackTrace() );

System.out.println( "End..." );
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks I got it. I think just() works with static values or if it is statement that must be evaluated before calling just() method.
I want the program to end in case of timeout exception, but the current one is still in running even after timeout error. Please suggest how to end the program running.
Since the blocking happens on the Java main thread outside the reach of RxJava, you have to run the getMsg() on a background thread. Updated the answer accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.