6

The code:

var shouldStopLoop = false

val handler = object : Handler()
val runnable = object: Runnable   // The error occurs here
{
    override fun run() {
        getSubsData()
        if(!shouldStopLoop)
        {
            handler.postDelayed(this, 5000)
        }
    }
}

handler.post(runnable)

The Expecting a class body error occurs while I am trying to create the val runnable.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
curiousgeek
  • 903
  • 11
  • 18

2 Answers2

9

The error occurs because you are treating Handler as an abstract class in the following statement:

val handler = object : Handler()

This statement needs a class body after it as the error says, like this:

val handler = object : Handler(){}

However, as Handler is not an abstract class, a more appropriate statement will be:

val handler = Handler()

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rahul Tiwari
  • 6,851
  • 3
  • 49
  • 78
3

You can try the following approach:

// This function takes a lambda extension function
// on class Runnable as the parameter. It is
// known as lambda with a receiver.
inline fun runnable(crossinline body: Runnable.() -> Unit) = object : Runnable {
    override fun run() = body()
}

fun usingRunnable() {
    val handler = Handler()
    val runnableCode = runnable {
        getSubsData()
        if(!shouldStopLoop)
        {
            handler.postDelayed(this, 5000)
        }
    }
    handler.post(runnableCode)
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sergio
  • 27,326
  • 8
  • 128
  • 149