ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Combine Operators 2(Replace)
    IOS/Combine 2024. 4. 21. 19:03

    안녕하세요 이번 글에선 Upstream 방출 값을 Replace하는 replaceNil, replaceEmpty를 알아보도록 하겠습니다.


    replaceNil(with:)

    - 옵셔널 값을 핸들링 할 때 사용되며 nil일 때 with파라미터의 지정된 값으로 변경할 수 있는 Operator입니다.

    ["A", nil, "C"].publisher
        .replaceNil(with: "-")
        .sink { print($0) }

     

    optional로 감싸져 있는 것을 unwrapping 하는 방법은 .eraseToAnyPublisher 및 with 파라미터에 as String으로 캐스팅 하는 방법이 있습니다.

    ["A", nil, "C"].publisher
        .eraseToAnyPublisher()
        .replaceNil(with: "-" )
        .sink { print($0 ?? "d") }
    
    
    ["A", nil, "C"].publisher
    //    .eraseToAnyPublisher()
        .replaceNil(with: "-" as String)
        .sink { print($0 ?? "d") }
    
    // OUTPUT 
    // A
    // -
    // C
    // A
    // -
    // C

    그렇다면 coalescing operator(??)를 사용해서 nil값을 처리하면 될거 같은 생각이 드는데요! replaceNil 사용해서 처리하면 

    nil값이 존재 하지 않음을 보장할 수 있습니다. 무슨말이냐면

    let optionalInt: Int? = nil
    let result: Int? = optionalInt ?? nil

    이렇게 ?? 연산자를 사용하면 nil값이 여전히 남아 있는 코드를 생성 할 수 있지만 replaceNil operator는 이런 현상을 방지 할 수 있습니다.


     

    replaceEmpty(with:)

    upstream에서 방출값이 없으면 with 파라미터(Int type)에 전달된 값으로 완료 이벤트 직전에 값을 방출하게 됩니다.

    Empty<Int, Never>()
    .sink(receiveCompletion: { print($0) },
          receiveValue: { print($0) })
          
    // OUTPUT: 
    // finished
    
    Empty<Int, Never>()
    .replaceEmpty(with: 1)
    .sink(receiveCompletion: { print($0) },
      receiveValue: { print($0) })
      
    // OUTPUT:
    // 1
    // finished

    ※Empty Publisher는 완료 이벤트를 subscriber에게 즉시 방출하는 Publisher입니다.

    'IOS > Combine' 카테고리의 다른 글

    Combine Operators 1 (transforming)  (0) 2024.04.13
    Combine Cancellable, subscription  (0) 2024.04.07
    Combine - Subscriber 2편  (0) 2024.03.30
    Combine - Subscriber 1편  (0) 2024.03.16
    Combine 구성요소 Publisher  (0) 2024.03.10
Designed by Tistory.