1

In Activity I have some kind of timeout for user action. If user do nothing I need produce some other action for system. For this I am using Handler

protected void stopTimeout()
{
    handler.removeMessages(0);
}

private void startTimeout()
{
    stopTimeout();
    handler.postDelayed(new Runnable()
    {
        @Override
        public void run()
        {
            //SOME ACTIONS
        }
    }, 180 * 1000L);
}

Handler can be stopped for some user actions like buttons click

    btnCancel.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            // user actions
            stopTimeout();
        }
    });

But at the moment I have to many variants of user actions. All this push to stopTimout from async threads and handler doesn't look as proper decision. Project I am already migrating to RXJava and

I can figure out how to done this part with RXJava.

2
  • Consider using removeMessagesAndCallbacks(null) for clearing the Handler. Commented Apr 14, 2016 at 7:36
  • callbacks hell, no thx, just removed all of this from project Commented Apr 14, 2016 at 8:40

2 Answers 2

2

Its simple:

subscription = Observable.timer(1000, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(aLong -> whatToDo());

private void whatToDo() {
   System.out.println("Called after 1 second");
}
Sign up to request clarification or add additional context in comments.

Comments

1

Start timer.

private void startTimeout() {
    stopTimeout();

    Observable<Long> observable = Observable
            .timer(getKeepMyOrderOnDisplayTime(),
                    TimeUnit.SECONDS, Schedulers.computation());
    cancelOrderSubscription = observable
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .map(new Func1<Long, MyOrderStorageItem>() {
                @Override
                public MyOrderStorageItem call(Long aLong) {
                    return myOrderStorageItem;
                }
            })
            .subscribe(new Action1<MyOrderStorageItem>() {
                @Override
                public void call(final MyOrderStorageItem myOrderStorageItem) {
                    // SOME ACTION with object, I need
                }
            });
}

Stop timer.

protected void stopTimeout() {
    if (cancelOrderSubscription != null) {
        cancelOrderSubscription.unsubscribe();
        cancelOrderSubscription = null;
    }
}

On user actions add stop timer run. If no user actions while timer, default action will.

Comments

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.