Search code examples
androidkotlinrunnableandroid-handler

How to resolve "expecting class body" error in kotlin


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.


Solution

  • 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)
    }