cozzin
코찐 기술 블로그
cozzin
전체 방문자
오늘
어제
  • 분류 전체보기
    • Kotlin
    • 백엔드
    • iOS
      • Swift
      • SwiftUI
      • Combine
      • Architecture
    • 개발환경
    • 세미나
    • 생각정리
    • 스터디
    • CS
      • Refactoring
      • OS

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • LinkedIn
  • 강의

공지사항

인기 글

태그

  • Warning
  • 리팩토링
  • CS
  • 운영체제
  • 디자인패턴
  • slide-over
  • os
  • Combine
  • 테스트
  • ios
  • darkmode
  • multicast
  • 워닝제거
  • XCode
  • 컴퓨터공학
  • WWDC21
  • WWDC
  • Swift
  • SwiftUI
  • Ribs

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
cozzin

코찐 기술 블로그

[Combine 책 정리] Chapter 13: Resource Management
iOS/Combine

[Combine 책 정리] Chapter 13: Resource Management

2021. 1. 27. 16:42
반응형

안녕하세요 코찐입니다.

아래의 자료를 따라서 공부하고 있습니다.

https://www.raywenderlich.com/books/combine-asynchronous-programming-with-swift/v2.0

 

리소스 관리하는 Publisher 들인데, API 작업할 때 유용하게 사용할 수 있습니다.

share

value 타입이 아닌 reference 타입의 publisher를 공유할 수 있도록 해줍니다.

주의할 점은 이미 complete 된 share publisher를 구독하면 complete만 받게 됩니다.

let shared = URLSession.shared
  .dataTaskPublisher(for: URL(string: "https://www.raywenderlich.com")!)
  .map(\.data)
  .print("shared")
  .share()

print("subscribing first")

let subscription1 = shared.sink(
  receiveCompletion: { _ in },
  receiveValue: { print("subscription1 received: '\($0)'") }
)

print("subscribing second")

let subscription2 = shared.sink(
  receiveCompletion: { _ in },
  receiveValue: { print("subscription2 received: '\($0)'") }
)
subscribing first
shared: receive subscription: (DataTaskPublisher)
shared: request unlimited
subscribing second
shared: receive value: (275400 bytes)
subscription1 received: '275400 bytes'
subscription2 received: '275400 bytes'
shared: receive finished

 

multicast

connect()를 호출해야 이벤트를 시작합니다.

그래서 subscription을 다 만들어두고, connect 할 수 있어서 편합니다.

let subject = PassthroughSubject<Data, URLError>()

let multicasted = URLSession.shared
    .dataTaskPublisher(for: URL(string: "https://www.raywenderlich.com")!)
    .map(\.data)
    .print("multicast")
    .multicast(subject: subject)

// 3
let subscription1 = multicasted
    .sink(
        receiveCompletion: { _ in },
        receiveValue: { print("subscription1 received: '\($0)'") }
    )

let subscription2 = multicasted
    .sink(
        receiveCompletion: { _ in },
        receiveValue: { print("subscription2 received: '\($0)'") }
    )

let cancellable = multicasted.connect()
multicast: receive subscription: (DataTaskPublisher)
multicast: request unlimited
multicast: receive value: (275400 bytes)
subscription1 received: '275400 bytes'
subscription2 received: '275400 bytes'
multicast: receive finished

 

future

future는 클로저 안의 동작을 즉시 실행합니다.

그리고 구독하면 그 값을 전달합니다.

 

func performSomeWork() throws -> Int {
    print("Performing some work and returning a result")
    return 5
}

let future = Future<Int, Error> { fulfill in
    do {
        let result = try performSomeWork()
        fulfill(.success(result))
    } catch {
        fulfill(.failure(error))
    }
}

print("Subscribing to future...")

let subscription1 = future
    .sink(
        receiveCompletion: { _ in print("subscription1 completed") },
        receiveValue: { print("subscription1 received: '\($0)'") }
    )

let subscription2 = future
    .sink(
        receiveCompletion: { _ in print("subscription2 completed") },
        receiveValue: { print("subscription2 received: '\($0)'") }
    )
Performing some work and returning a result
Subscribing to future...
subscription1 received: '5'
subscription1 completed
subscription2 received: '5'
subscription2 completed

 

 

 

반응형
저작자표시 (새창열림)

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

[Combine] Chapter 17: Schedulers  (0) 2021.02.03
[Combine] Chapter 16: Error Handling  (0) 2021.02.01
[Combine 책 정리] Chapter 12: Key-Value Observing  (0) 2021.01.27
[Combine 책 정리] Chapter 11: Timers  (0) 2021.01.27
[Combine 책 정리] Chapter 10: Debugging  (0) 2021.01.27
    'iOS/Combine' 카테고리의 다른 글
    • [Combine] Chapter 17: Schedulers
    • [Combine] Chapter 16: Error Handling
    • [Combine 책 정리] Chapter 12: Key-Value Observing
    • [Combine 책 정리] Chapter 11: Timers
    cozzin
    cozzin
    Software Engineer

    티스토리툴바