반응형
defer
구독될 때마다 새로운 Flowable/Observable을 생성하는 연산자이다. just와는 다르게 선언한 시점의 데이터를 통지하는 것이 아니라 호출 시점에 데이터 생성이 필요할 때 사용한다.
[소스코드]
public class Main {
public static void main(String[] args) throws Exception {
defer();
justTime();
}
static void defer() throws Exception {
System.out.println("defer() locaTime");
Flowable<LocalTime> flowable = Flowable.defer(() -> Flowable.just(LocalTime.now()));
flowable.subscribe(new PrintSubscriber<>("Label 1"));
Thread.sleep(3000L);
flowable.subscribe(new PrintSubscriber<>("Label 2"));
}
static void justTime() throws Exception {
System.out.println("just() locaTime");
Flowable<LocalTime> flowable = Flowable.just(LocalTime.now());
flowable.subscribe(new PrintSubscriber<>("Label 1"));
Thread.sleep(3000L);
flowable.subscribe(new PrintSubscriber<>("Label 2"));
}
[Subscribe 코드]
import io.reactivex.subscribers.DisposableSubscriber;
public class PrintSubscriber<T> extends DisposableSubscriber<T> {
private String label;
public PrintSubscriber() {
}
public PrintSubscriber(String label) {
this.label = label;
}
@Override
public void onNext(T data) {
String threadName = Thread.currentThread().getName();
String resultMsg = label == null ? (threadName + " : " + data) : (threadName + " : "+ label + " : "+ data);
System.out.println(resultMsg);
}
@Override
public void onError(Throwable throwable) {
String threadName = Thread.currentThread().getName();
String resultMsg = label == null ? (threadName + " : Exception=" + throwable) : (threadName + " : "+ label + " : "+ throwable);
System.out.println(resultMsg);
}
@Override
public void onComplete() {
String threadName = Thread.currentThread().getName();
String resultMsg = label == null ? (threadName + " : Complete") : (threadName + " : "+ label + " : Complete");
System.out.println(resultMsg);
}
}
[결과]
defer just를 보면 just는 기존 Flowable을 사용하고 defer는 Flowable을 새로만들어 사용하고 있는 것을 확인할 수 있다.
defer() locaTime
main : Label 1 : 15:40:52.764
main : Label 1 : Complete
main : Label 2 : 15:40:55.767
main : Label 2 : Complete
just() locaTime
main : Label 1 : 15:40:55.767
main : Label 1 : Complete
main : Label 2 : 15:40:55.767
main : Label 2 : Complete
반응형
'Language > Java' 카테고리의 다른 글
[RxJava] never (0) | 2023.04.26 |
---|---|
[RxJava] empty (0) | 2023.04.26 |
[RxJava] timer (0) | 2023.04.26 |
[RxJava] interval (0) | 2023.04.26 |
[RxJava] range, rangeLong (0) | 2023.04.26 |