Publishers.Decode

μ œλ„€λ¦­ ꡬ쑰체

μ΄λ‹ˆμ…œλΌμ΄μ €λŠ” 두 개의 인자λ₯Ό λ°›λŠ”λ‹€.

  • upstream: μƒμœ„μ— 흐λ₯΄λŠ” Publisher

  • decoder : μ‚¬μš©ν•  디코더

decoderλŠ” Combine의 TopLevelDecoder ν”„λ‘œν† μ½œμ„ 채택해야 ν•˜λŠ”λ°, ν˜„μž¬ JSONDecoder와 PropertyListDecoderκ°€ 이 ν”„λ‘œν† μ½œμ„ μ±„νƒν•˜κ³  μžˆλ‹€.

μƒμœ„ 슀트림의 μš”μ†Œλ₯Ό λ””μ½”λ”©ν•˜κΈ° μœ„ν•΄ μ‚¬μš©ν•  수 μžˆλ‹€.

decode μ˜€νΌλ ˆμ΄ν„°μ™€ 관련이 μžˆλ‹€.

struct SimpleJSON: Decodable {
  let key: String
}
let jsonData = "{ \"key\": \"value\" }".data(using: .utf8)!

// Publishers.Decode Publisher
Publishers.Decode<Just<JSONDecoder.Input>, SimpleJSON, JSONDecoder>(upstream: Just(jsonData), decoder: JSONDecoder())
  .sink(receiveCompletion: { completion in
    switch completion {
    case .failure:
      print("Combine Decode Error")
    case .finished:
      print("Combine Decode Finish")
    }
  }, receiveValue: { value in
    print("Combine Decode : \(value)")
  })
  .store(in: &cancellables)

// encode Operator
Just(jsonData)
  .decode(type: SimpleJSON.self, decoder: JSONDecoder())
  .sink(receiveCompletion: { completion in
    switch completion {
    case .failure:
      print("Combine Decode Error")
    case .finished:
      print("Combine Decode Finish")
    }
  }, receiveValue: { value in
    print("Combine Decode : \(value)")
  })
  .store(in: &cancellables)

// Combine Decode : SimpleJSON(key: "value")
// Combine Decode Finish

μƒμœ„ PublisherλŠ” JSON ν˜•μ‹μ˜ 데이터λ₯Ό κ°–λŠ” Dataλ₯Ό λ°œν–‰ν•˜λ©°, JSONDecoderλ₯Ό μ‚¬μš©ν•˜μ—¬ λ””μ½”λ”©ν•œλ‹€.

RxSwift

ν•΄λ‹Ή κΈ°λŠ₯을 κ΅¬ν˜„ν•˜κΈ° μœ„ν•œ μ˜€νΌλ ˆμ΄ν„°λ₯Ό μ œκ³΅ν•˜μ§€ μ•ŠλŠ”λ‹€.

ReactiveSwift

ν•΄λ‹Ή κΈ°λŠ₯을 κ΅¬ν˜„ν•˜κΈ° μœ„ν•œ μ˜€νΌλ ˆμ΄ν„°λ₯Ό μ œκ³΅ν•˜μ§€ μ•ŠλŠ”λ‹€.

Last updated