거꾸로 바라본 세상
Published 2023. 4. 26. 09:37
[RxJava] map Language/Java
반응형

map

원본 Flowable/Observable에서 통지하는 데이터를 변환한 후 데이터를 통지하는 연산자로 flatMap과 달리 한 개의 데이터로 여러 데이터를 생성하여 통지하거나 데이터 통지를 건너뛸 수 없다. 데이터를 받으면 반드시 null이 아닌 데이터 하나를 반환해야 한다.

map

Flowable/Observable의 메서드

//map method
public final <R> Flowable<R> map(Function<? super T, ? extends R> mapper)

//Function
new Function<String, BigInteger>() {
    @Override
    public BigInteger apply(String data) throws Exception {
        return null;
    }
};

[소스코드]

public class Main {
    public static void main(String[] args) {
        map();
    }

    static void map() {
        System.out.println("flowable");
        Flowable<String> flowable = Flowable.just("A", "B", "C").map(String::toLowerCase);
        flowable.subscribe(new PrintSubscriber<>());
        System.out.println("flowable1");
        Flowable<String> flowable1 = Flowable.just("A", "B", "C").map(null); //Null Pint Exception!!
        flowable1.subscribe(new PrintSubscriber<>());
    }
}

[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);
    }
}

[결과]

flowable
main : a
main : b
main : c
main : Complete
flowable1
Exception in thread "main" java.lang.NullPointerException: mapper is null
    at io.reactivex.internal.functions.ObjectHelper.requireNonNull(ObjectHelper.java:39)
    at io.reactivex.Flowable.map(Flowable.java:11352)
    at rx2.Main.map(Main.java:15)
    at rx2.Main.main(Main.java:7)

map 은 리턴 데이터가 null 인경우 NullPointException을 발생시키는 것을 확인할 수 있다.

반응형

'Language > Java' 카테고리의 다른 글

[RxJava] concatMap / concatMapDelayError  (0) 2023.04.26
[RxJava] flatMap  (0) 2023.04.26
[RxJava] never  (0) 2023.04.26
[RxJava] empty  (0) 2023.04.26
[RxJava] defer  (0) 2023.04.26
profile

거꾸로 바라본 세상

@란지에。

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!