Convert infinitely running Runnable from java to kotlin

I have a code like this in java that monitors a specific file:

private Handler mHandler = new Handler();
private final Runnable monitor = new Runnable() {

    public void run() {
        // Do my stuff
        mHandler.postDelayed(monitor, 1000); // 1 second
    }
};

      

This is my kotlin code:

private val mHandler = Handler()
val monitor: Runnable = Runnable {
    // do my stuff
    mHandler.postDelayed(whatToDoHere, 1000) // 1 second
}

      

I do not understand what Runnable

I should go to mHandler.postDelayed

. What's the correct decision? Another interesting thing: the kotlin to java converter hangs when I feed this code.

+3


source to share


2 answers


Lambda expressions don't have this

, but anonymous classes do.



object : Runnable {
    override fun run() {
        handler.postDelayed(this, 1000)
    }
}

      

+5


source


A slightly different approach that might be more readable

val timer = Timer()
val monitor = object : TimerTask() {
    override fun run() {
        // whatever you need to do every second
    }
}

timer.schedule(monitor, 1000, 1000)

      



From: Repeat action every 2 seconds in java

+3


source







All Articles