This repository has been archived by the owner on Dec 26, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
ラムダ式を使う
Yuya Matsuo edited this page Sep 23, 2016
·
5 revisions
GLスレッドとバックグラウンドスレッドとUIスレッドを行ったり来たりすると、どんどんnew Runnable()
のネストが深くなってコードが読みづらくなります。ラムダ式を使うことでRunnable
を扱うコードが簡素化されてネストも浅くなります。
runOnGlThread(new Runnable() {
public void run() {
// do something
}
});
Threads.spawn(new Runnable() {
public void run() {
// do in background
// in background
// ...
// later
app.runOnGlThread(new Runnable() {
public void run() {
updateScene(result);
}
});
}
});
runOnGlThread(() -> {
// do something
});
Threads.spawn(() -> {
// do something
// in background
// ...
// later
app.runOnGlThread(() -> updateScene(result));
});
ラムダ式はJava8で導入された機能で、Android Nから利用できるようになる予定です。しかしJava7以前の古い実行環境向けにラムダ式を変換するRetrolambdaを使うことでAndroid N以前でもラムダ式を利用できます。
アプリのbuild.gradleの冒頭部分を以下のように書き換えます
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
classpath 'me.tatarka:gradle-retrolambda:3.2.5'
}
}
// Required because retrolambda is on maven central
repositories {
mavenCentral()
}
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
...
android {
...
// Java8でコンパイルするように設定
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Retrolambdaを使わなくてもJackツールチェインを使うことでラムダ式を使えます。こちらの方が設定が少ないのでおすすめです。 Jackツールチェインを使うには、モジュールのbuild.gradleに以下の項目を追加します。
android {
...
defaultConfig {
...
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}