Skip to content

Instantly share code, notes, and snippets.

@djds23
Last active November 15, 2018 15:23
Show Gist options
  • Select an option

  • Save djds23/bf50f0d14aa8da8f47a8d9b372a7e931 to your computer and use it in GitHub Desktop.

Select an option

Save djds23/bf50f0d14aa8da8f47a8d9b372a7e931 to your computer and use it in GitHub Desktop.
Let Me Check My Scheduler
final class FollowUserViewModel {
// Observer for our view to bind to when our user
  // wants to follow another user.
  let followUserObserver: AnyObserver<User> {
  return followSubject.asObserver()
  }
private let disposeBag = DisposeBag()
  // This subject will listen for users to follow.
  private let followSubject = PublishSubject<User>()
  init(user: User, networkHandler: FollowNetworkHandler) {
  // Create an operation queue to do work on
  let operationQueue = OperationQueue()
  operationQueue.maxConcurrentOperationCount = 20
  // Set it to the .userInitiated Quality Of Service
  operationQueue.qualityOfService = .userInitiated
  // Create a scheduler with our new OperationQueue
// A Scheduler defines what queue our work will happen on.
// By specifying our background scheduler, we ensure work will
// not block interaction with the user.
  let backgroundScheduler = OperationQueueScheduler(
  operationQueue: operationQueue
  )
  followSubject
  // Perform our work onto the our scheduler
  .observeOn(backgroundScheduler)
  .do(onNext: { [weak self] user in
  // Perform the follow when an event comes in.
  networkHandler.follow(user: user)
  })
  .subscribe()
  .disposed(by: disposeBag)
 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment