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

Was this helpful?