Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upgrading a Handler with Runnable to lambda expression

I want to upgrade this code to use a lambda expression:

Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        missileX = ufoX;
        resetRecent();
        waitForUfoTimer = false;
    }
}, randomize(20000, 18000));

I try it this way but it doesn't compile:

Handler handler2 = new Handler(Looper.getMainLooper());
handler2.postDelayed(Runnable task = () -> {  
    missileX = ufoX;
    resetRecent();
    waitForUfoTimer = false; 
  }
}, randomize(20000, 18000));

Where are some instructions so that I can learn how to do it? It is preposterous that I must guess the syntax.

like image 276
Niklas Rosencrantz Avatar asked May 19 '26 13:05

Niklas Rosencrantz


1 Answers

You don't have to declare a variable to assign to the lambda. This is enough :

Handler handler2 = new Handler(Looper.getMainLooper());
handler2.postDelayed(() -> {  
    missileX = ufoX;
    resetRecent();
    waitForUfoTimer = false; 
  }
, randomize(20000, 18000));
like image 161
davidxxx Avatar answered May 22 '26 02:05

davidxxx