28

I have some code like this in java that monitors a certain 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 dont understand what Runnable I should pass into mHandler.postDelayed. What is the right solution? Another interesting thing is that the kotlin to java convertor freezes when I feed this code.

Binoy Babu
  • 16,699
  • 17
  • 91
  • 134
  • 2
    There was an interesting discussion about this same issue recently: https://stackoverflow.com/questions/35100389/writing-a-kotlin-util-function-which-provides-self-reference-in-initializer – Sam Jun 27 '17 at 21:00

5 Answers5

48

Lambda-expressions do not have this, but object expressions (anonymous classes) do.

object : Runnable {
    override fun run() {
        handler.postDelayed(this, 1000)
    }
}
Miha_x64
  • 5,973
  • 1
  • 41
  • 63
9

A slightly different approach which may 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 an action every 2 seconds in java

Hobo Joe
  • 737
  • 1
  • 9
  • 11
2

runnable display Toast Message "Hello World every 4 seconds

//Inside a class main activity

    val handler: Handler = Handler()
    val run = object : Runnable {
       override fun run() {
           val message: String = "Hello World" // your message
           handler.postDelayed(this, 4000)// 4 seconds
           Toast.makeText(this@MainActivity,message,Toast.LENGTH_SHORT).show() // toast method
       }

   }
    handler.post(run)
}
KaZaiya
  • 59
  • 6
1

Lambda-expressions do not have this, but object expressions (anonymous classes) do. Then the corrected code would be:

private val mHandler = Handler()
val monitor: Runnable = object : Runnable{
 override fun run() {
                   //any action
                }
                //runnable

            }

 mHandler.postDelayed(monitor, 1000)
taranjeetsapra
  • 524
  • 7
  • 19
0
var handler=Handler() 
handler.postDelayed(Runnable { kotlin.run { 

// enter code here

} },2000)
Robert Columbia
  • 6,313
  • 15
  • 32
  • 40