Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. enum MyError: Error {
  2. case whoops
  3. }
  4.  
  5. //Observable.create {}
  6. let o = AnyPublisher<Int, MyError> { subscriber in
  7. /*
  8. onNext, but in combine you are returned a demand,
  9. this is for controlling backpressure, which
  10. doesn't exist in RxSwift.
  11.  
  12. someone on the combine team mentioned the implementation
  13. was more inspired by Reactive Streams implementations
  14. (think Akka) where backpressure is a thing.
  15. there's a very good reason apple chose this, because
  16. it's a weird concept for sure
  17. */
  18. let demand = subscriber.receive(1)
  19. print(demand)
  20. let _ = subscriber.receive(2)
  21. let _ = subscriber.receive(3)
  22. let _ = subscriber.receive(4)
  23.  
  24. //onComplete
  25. subscriber.receive(completion: .finished)
  26. /*
  27. alternatively if you want to send an error,
  28. although it appears you can send both a completion and
  29. a failure and the runtime doesn't seem to care
  30. in RxSwift, this would assert in debug
  31. subscriber.receive(completion: .failure(.whoops))
  32. */
  33.  
  34. }
  35.  
  36. /*
  37. ok now is where things get weird.
  38.  
  39. i'll explain this optional later.
  40. */
  41. var s: Subscribers.Sink<AnyPublisher<Int, MyError>>? = nil
  42.  
  43. /*
  44. subscribe(onNext:{}, onError: {}, onCompleted: {})
  45. but combine sends the complete/error events to the same closure,
  46. and it's the first argument, probably because the most common use case is just
  47. the onNext case. e.g., o.sink { val in print(val) }
  48. */
  49. s = o.sink(receiveCompletion: { result in
  50. switch result {
  51. case .finished:
  52. print("completed")
  53. case let .failure(f):
  54. print("error \(f)")
  55. }
  56. }, receiveValue: { int in
  57. print(int)
  58. })
  59.  
  60. /*
  61. silencing a compiler warning, "s" is never read
  62. */
  63. print(String(describing:s))
  64.  
  65. /*
  66. Subscribers have reference type semantics (are classes) so disposal follows the same rules as ARC
  67. setting this to nil disposes the subscription.
  68.  
  69. BUT!!! not in this code because everytning is running on the immediate scheduler.
  70. * i think *
  71. */
  72. s = nil
  73.  
  74. /*
  75. things like Observable.just, Observable.empty are found in the Publishers enum
  76. so like Observable.just is Publishers.Just, Observable.empty is Publishers.empty
  77. there's a futures like creator, that is like a single: Publishers.Future
  78. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement