ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Combine - Scheduler
    Combine 2022. 3. 7. 21:04

    안녕하세요. 그린입니다🟢

    이번 포스팅에서는 Combine에서 크게 알아보기로한 4번째 친구 Scheduler에 대해 학습해보겠습니다!🙌

    Scheduler?

    공식문서에 따르면 클로저를 실행하는 시기와 방법을 정의하는 프로토콜이라고 합니다.

    protocol Scheduler

    이렇게 간단히 선언을 보면 프로토콜입니다!

    자 생각해보면 우리가 흔히 사용하던 DispatchQueue나 OperationQueue와 동일한 역할이라고 생각이 듭니다.

    즉 메인 혹은 서브 쓰레드 어디에서 해당 클로저를 실행해줄지에 대한거라고 이해하면 쉬울것 같아요.

     

    공식문서의 OverView 전문을 가져와볼께요!

     

    You can use a scheduler to execute code as soon as possible, or after a future date. Individual scheduler implementations use whatever time-keeping system makes sense for them. Schedulers express this as their SchedulerTimeType. Since this type conforms to SchedulerTimeIntervalConvertible, you can always express these times with the convenience functions like .milliseconds(500). Schedulers can accept options to control how they execute the actions passed to them. These options may control factors like which threads or dispatch queues execute the actions.

    이게 설명이 끝이지만... 한번 어떤 개요를 가졌는지 중요한 부분만 간추려서 해석을 해보겠습니다.

    1. 스케쥴러를 사용해 최대한 빠르게 혹은 원하는 이후에 코드 실행이 가능하다.

    2. 개별 스케쥴러 구현은 시간 관리 시스템에 알맞는걸 택하면 된다.

    3. 스케쥴러에 옵션을 부여해 작업 수행하는 스레드나 디스패치 큐와 같은 요소를 제어할 수 있다.

     

    뭐 어렵지 않죠?

    즉, 정리하자면 스케쥴러는 해당 작업을 어느 시간에 어떤 스레드에서 작업이 진행될지 정해주는 역할을 합니다🙌

    Scheduler의 기본 속성

    스케쥴러를 쉽게 사용하는 방법으로는 직접 구현보다 애플이 아주 친절히(?) 잘 만들어놓은 디스패치큐, 오퍼레이션큐, 런루프 등등으로

    이용해줄 수 있습니다.

    우선 스케쥴러에 대한 알아야할 특성이 하나 있습니다.

    Combine에서는 스케쥴러를 설정해주지 않는다면 기본 스케쥴러를 따릅니다.

    무슨말이냐..! 즉, 방출하는 작업이 이뤄지는 스레드가 기본 스케쥴러의 스레드가 됩니다.

    Scheduler의 사용

    스케쥴러를 기본적으로 사용하지 않고 예를들어 원하는 스레드에서 작업할 수 있도록 변화를 주고싶다면,

    두가지 방법으로 설정해주면 됩니다.

    receive(on:) & subscribe(on:)

    두가지 모두 사용되는 방법은 동일하기에 receive(on:)으로만 예시를 들어보겠습니다!

    // main thread
    publisher
      .receive(on: DispatchQueue.main())
      
    // global thread
    publisher
      .receive(on: DispatchQueue.global())

    아주 간단해요.

    이렇게 사용해주면 기본 사용은 완성입니다.

    마무리

    스케쥴러는 뭔가 개념에 대해 한번 짚고 간 느낌이 있습니다.

    딥하게 들어가면 receive와 subscribe에서의 설정 차이, 다운 혹은 업스트림에 대해서도 많이 알아야겠지만

    우선 이번에는 간략히 빨리 익히기 위해 이정도까지 알아봤습니다!

    설명이 잘못된 부분은 댓글로 언제든 알려주시면 감사하겠습니다🙇🏻

    [참고자료]

    https://developer.apple.com/documentation/combine/scheduler

     

    Apple Developer Documentation

     

    developer.apple.com

     

    'Combine' 카테고리의 다른 글

    Combine - ObservableObject / @Published / @ObservedObject  (0) 2022.03.17
    Combine - Cancellable  (2) 2022.03.10
    Combine - Subject  (0) 2022.02.28
    Combine - Subscriber  (0) 2022.02.24
    Combine - Publisher  (0) 2022.02.22
Designed by Tistory.