개발하는 두더지

[Java/Android] Java8 Lambda 사용법 본문

Java,Android

[Java/Android] Java8 Lambda 사용법

덜지 2018. 4. 27. 11:38

Java8 Lambda

Java8에서 Lambda 표현식을 지원합니다.

이전 버전에서는 익명 클래스로 구현해야했습니다.



build.gradle 설정

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}


예를들어 버튼에 클릭리스너를 달아준다고 했을 때 보통 아래처럼 사용합니다.

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

}
});


Lambda를 쓴다면?

btn.setOnClickListener( 
v -> {

}
);
btn.setOnClickListener(
(View v) -> {

}
);

Runnable runnable = () -> {
System.out.println("Hello Runnable");
};
new Thread(runnable).start();

new Thread(
() -> System.out.println("Hello Runnable2")
).start();

new Thread(
() -> { System.out.println("Hello Runnable3"); }
).start();


위와 같이 Lambda 표현법은 여러가지가 있습니다.


( ) -> { }


( a ) -> { }


( int a ) -> { }


a -> { }


() -> { System.out.println("Hello"); }


() -> System.out.println("Hello")




하지만 Lambda 표현식을 쓰기 위해서 제약 조건이 있습니다.

1개의 메소드를 가진 Interface 이어야 합니다.




RxJava2 + Lambda 여러가지 사용 예시

public void emit() {
Observable<String> source = Observable.just("RED", "GREEN", "YELLOW");

Disposable d = source.subscribe(
v -> System.out.println("onNext() : v : " + v),
err -> System.err.println("onError() : err : " + err.getMessage()),
() -> System.out.println("onComplete()")
) ;

System.out.println("isDisposed() : " + d.isDisposed());
}


public void emit2() {
/*ObservableOnSubscribe observableOnSubscribe = new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter emitter) throws Exception {

}
};*/

Observable<Integer> source = Observable.create(
emitter -> {
emitter.onNext(100);
emitter.onNext(200);
emitter.onNext(300);
emitter.onNext(400);
emitter.onComplete();
}
);

Disposable d = source.subscribe(
v -> System.out.println("onNext() : " + v)
);
}



public void emit3() {
int[] arr = {100, 200, 300};
Observable.fromArray(toIntegerArray(arr))
.subscribe(data -> System.out.println(data));
}

private static Integer[] toIntegerArray(int[] intArray) {
Integer[] integerArray = new Integer[intArray.length];
for(int i = 0; i < intArray.length; i++) {
integerArray[i] = intArray[i];
}
return integerArray;

}


public void emit4() {
List<String> names = new ArrayList<>();
names.add("Jerry");
names.add("Kim");
names.add("Joy");

Observable.fromIterable(names)
.subscribe(System.out::println);
}



public void emit5() {
Callable<String> callable = () -> {
Thread.sleep(1000);
return "Hello Callable";
};

Observable.fromCallable(callable)
.doOnComplete( () -> System.out.println("Hello Callable complete!"))
.subscribe(System.out::println);
}



public void emit6() {
Observable.fromCallable(() -> {return "Hello Callable";})
.subscribe(System.out::println);
}


public void emit8() {
Future<String> future = Executors.newSingleThreadExecutor().submit(
() -> {
Thread.sleep(1000);
return "Hello Future";
}
);
Observable.fromFuture(future)
.subscribe(System.out::println);
}



public void emit9() {

Observable.fromFuture(Executors.newSingleThreadExecutor().submit( () -> {
return "Hello Futrue2";
})).subscribe(System.out::println);
}


public void emit10() {
/*Publisher<String> publisher = new Publisher<String>() {
@Override
public void subscribe(Subscriber<? super String> s) {
s.onNext("Hello Observable.fromPublisher()");
s.onComplete();
}
}*/

Publisher<String> publisher = (Subscriber<? super String> s) -> {
s.onNext("Hello Observable.fromPublisher()");
s.onComplete();
};
Observable<String> source = Observable.fromPublisher(publisher);
source.subscribe(System.out::println);
}


참고

Lambda 와 RetroLambda by 정상욱님



Comments