URLSession.DataTaskPublisher

๊ตฌ์กฐ์ฒด | URL ์„ธ์…˜ ๋ฐ์ดํ„ฐ ์ž‘์—…์˜ ์ˆ˜ํ–‰ ๊ฒฐ๊ณผ๋ฅผ ์ „๋‹ฌํ•˜๋Š” Publisher

์ด๋‹ˆ์…œ๋ผ์ด์ €๋Š” ๋‘ ๊ฐœ์˜ ์ธ์ž๋ฅผ ๋ฐ›๋Š”๋‹ค.

  • request : URLRequest ๊ฐ์ฒด

  • session : URLSession ๊ฐ์ฒด

๊ธฐ์กด URLSession.dataTask ์ž‘์—…์„ Publisher๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด์ค€๋‹ค.

URLSession์˜ dataTaskPublisher ๋ฉ”์†Œ๋“œ๋กœ ํ•ด๋‹น Publisher๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค. ํ•ด๋‹น ๋ฉ”์†Œ๋“œ๋Š” URL ๋˜๋Š” URLRequest ๊ฐ์ฒด๋ฅผ ์ธ์ž๋กœ ๋ฐ›๋Š”๋‹ค.

// URLSession.DataTaskPublisher Publisher
let session = URLSession.shared
let request = URLRequest(url: url)
URLSession.DataTaskPublisher(request: request, session: session)
  .sink(receiveCompletion: { completion in
    switch completion {
    case .failure:
      print("Combine DataTaskPublisher Error")
    case .finished:
      print("Combine DataTaskPublisher Finish")
    }
  }, receiveValue: { value in
    print("Combine DataTaskPublisher : \(value)")
  })
  .store(in: &cancellables)

// dataTaskPublisher Property
URLSession.shared.dataTaskPublisher(for: url)
  .sink(receiveCompletion: { completion in
    switch completion {
    case .failure:
      print("Combine DataTaskPublisher Error")
    case .finished:
      print("Combine DataTaskPublisher Finish")
    }
  }, receiveValue: { value in
    print("Combine DataTaskPublisher : \(value)")
  })
  .store(in: &cancellables)

Last updated