You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

649 lines
16 KiB

2 years ago
  1. [![CircleCI](https://img.shields.io/circleci/project/github/RxSwiftCommunity/RxSwiftExt/main.svg)](https://circleci.com/gh/RxSwiftCommunity/RxSwiftExt/tree/main)
  2. ![pod](https://img.shields.io/cocoapods/v/RxSwiftExt.svg)
  3. [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
  4. RxSwiftExt
  5. ===========
  6. If you're using [RxSwift](https://github.com/ReactiveX/RxSwift), you may have encountered situations where the built-in operators do not bring the exact functionality you want. The RxSwift core is being intentionally kept as compact as possible to avoid bloat. This repository's purpose is to provide additional convenience operators and Reactive Extensions.
  7. Installation
  8. ===========
  9. This branch of RxSwiftExt targets Swift 5.x and RxSwift 5.0.0 or later.
  10. * If you're looking for the Swift 4 version of RxSwiftExt, please use version `3.4.0` of the framework.
  11. #### CocoaPods
  12. Add to your `Podfile`:
  13. ```ruby
  14. pod 'RxSwiftExt', '~> 5'
  15. ```
  16. This will install both the `RxSwift` and `RxCocoa` extensions.
  17. If you're interested in only installing the `RxSwift` extensions, without the `RxCocoa` extensions, simply use:
  18. ```ruby
  19. pod 'RxSwiftExt/Core'
  20. ```
  21. Using Swift 4:
  22. ```ruby
  23. pod 'RxSwiftExt', '~> 3'
  24. ```
  25. #### Carthage
  26. Add this to your `Cartfile`
  27. ```
  28. github "RxSwiftCommunity/RxSwiftExt"
  29. ```
  30. Operators
  31. ===========
  32. RxSwiftExt is all about adding operators and Reactive Extensions to [RxSwift](https://github.com/ReactiveX/RxSwift)!
  33. ## Operators
  34. These operators are much like the RxSwift & RxCocoa core operators, but provide additional useful abilities to your Rx arsenal.
  35. * [unwrap](#unwrap)
  36. * [ignore](#ignore)
  37. * [ignoreWhen](#ignorewhen)
  38. * [Observable.once](#once)
  39. * [distinct](#distinct)
  40. * [map](#map)
  41. * [not](#not)
  42. * [and](#and)
  43. * [Observable.cascade](#cascade)
  44. * [pairwise](#pairwise)
  45. * [nwise](#nwise)
  46. * [retry](#retry)
  47. * [repeatWithBehavior](#repeatwithbehavior)
  48. * [catchErrorJustComplete](#catcherrorjustcomplete)
  49. * [pausable](#pausable)
  50. * [pausableBuffered](#pausablebuffered)
  51. * [apply](#apply)
  52. * [filterMap](#filtermap)
  53. * [Observable.fromAsync](#fromasync)
  54. * [Observable.zip(with:)](#zipwith)
  55. * [Observable.merge(with:)](#mergewith)
  56. * [count](#count)
  57. * [partition](#partition)
  58. * [bufferWithTrigger](#bufferWithTrigger)
  59. There are two more available operators for `materialize()`'d sequences:
  60. * [errors](#errors-elements)
  61. * [elements](#errors-elements)
  62. Read below for details about each operator.
  63. ## Reactive Extensions
  64. RxSwift/RxCocoa Reactive Extensions are provided to enhance existing objects and classes from the Apple-ecosystem with Reactive abilities.
  65. * [UIViewPropertyAnimator.animate](#uiviewpropertyanimatoranimate)
  66. * [UIScrollView.reachedBottom](#uiscrollviewreachedbottom)
  67. --------
  68. Operator details
  69. ===========
  70. #### unwrap
  71. Unwrap optionals and filter out nil values.
  72. ```swift
  73. Observable.of(1,2,nil,Int?(4))
  74. .unwrap()
  75. .subscribe { print($0) }
  76. ```
  77. ```
  78. next(1)
  79. next(2)
  80. next(4)
  81. ```
  82. #### ignore
  83. Ignore specific elements.
  84. ```swift
  85. Observable.from(["One","Two","Three"])
  86. .ignore("Two")
  87. .subscribe { print($0) }
  88. ```
  89. ```
  90. next(One)
  91. next(Three)
  92. completed
  93. ```
  94. #### ignoreWhen
  95. Ignore elements according to closure.
  96. ```swift
  97. Observable<Int>
  98. .of(1,2,3,4,5,6)
  99. .ignoreWhen { $0 > 2 && $0 < 6 }
  100. .subscribe { print($0) }
  101. ```
  102. ```
  103. next(1)
  104. next(2)
  105. next(6)
  106. completed
  107. ```
  108. #### once
  109. Send a next element exactly once to the first subscriber that takes it. Further subscribers get an empty sequence.
  110. ```swift
  111. let obs = Observable.once("Hello world")
  112. print("First")
  113. obs.subscribe { print($0) }
  114. print("Second")
  115. obs.subscribe { print($0) }
  116. ```
  117. ```
  118. First
  119. next(Hello world)
  120. completed
  121. Second
  122. completed
  123. ```
  124. #### distinct
  125. Pass elements through only if they were never seen before in the sequence.
  126. ```swift
  127. Observable.of("a","b","a","c","b","a","d")
  128. .distinct()
  129. .subscribe { print($0) }
  130. ```
  131. ```
  132. next(a)
  133. next(b)
  134. next(c)
  135. next(d)
  136. completed
  137. ```
  138. #### mapTo
  139. Replace every element with the provided value.
  140. ```swift
  141. Observable.of(1,2,3)
  142. .mapTo("Nope.")
  143. .subscribe { print($0) }
  144. ```
  145. ```
  146. next(Nope.)
  147. next(Nope.)
  148. next(Nope.)
  149. completed
  150. ```
  151. #### mapAt
  152. Transform every element to the value at the provided key path.
  153. ```swift
  154. struct Person {
  155. let name: String
  156. }
  157. Observable
  158. .of(
  159. Person(name: "Bart"),
  160. Person(name: "Lisa"),
  161. Person(name: "Maggie")
  162. )
  163. .mapAt(\.name)
  164. .subscribe { print($0) }
  165. ```
  166. ```
  167. next(Bart)
  168. next(Lisa)
  169. next(Maggie)
  170. completed
  171. ```
  172. #### not
  173. Negate booleans.
  174. ```swift
  175. Observable.just(false)
  176. .not()
  177. .subscribe { print($0) }
  178. ```
  179. ```
  180. next(true)
  181. completed
  182. ```
  183. #### and
  184. Verifies that every value emitted is `true`
  185. ```swift
  186. Observable.of(true, true)
  187. .and()
  188. .subscribe { print($0) }
  189. Observable.of(true, false)
  190. .and()
  191. .subscribe { print($0) }
  192. Observable<Bool>.empty()
  193. .and()
  194. .subscribe { print($0) }
  195. ```
  196. Returns a `Maybe<Bool>`:
  197. ```
  198. success(true)
  199. success(false)
  200. completed
  201. ```
  202. #### cascade
  203. Sequentially cascade through a list of observables, dropping previous subscriptions as soon as an observable further down the list starts emitting elements.
  204. ```swift
  205. let a = PublishSubject<String>()
  206. let b = PublishSubject<String>()
  207. let c = PublishSubject<String>()
  208. Observable.cascade([a,b,c])
  209. .subscribe { print($0) }
  210. a.onNext("a:1")
  211. a.onNext("a:2")
  212. b.onNext("b:1")
  213. a.onNext("a:3")
  214. c.onNext("c:1")
  215. a.onNext("a:4")
  216. b.onNext("b:4")
  217. c.onNext("c:2")
  218. ```
  219. ```
  220. next(a:1)
  221. next(a:2)
  222. next(b:1)
  223. next(c:1)
  224. next(c:2)
  225. ```
  226. #### pairwise
  227. Groups elements emitted by an Observable into arrays, where each array consists of the last 2 consecutive items; similar to a sliding window.
  228. ```swift
  229. Observable.from([1, 2, 3, 4, 5, 6])
  230. .pairwise()
  231. .subscribe { print($0) }
  232. ```
  233. ```
  234. next((1, 2))
  235. next((2, 3))
  236. next((3, 4))
  237. next((4, 5))
  238. next((5, 6))
  239. completed
  240. ```
  241. #### nwise
  242. Groups elements emitted by an Observable into arrays, where each array consists of the last N consecutive items; similar to a sliding window.
  243. ```swift
  244. Observable.from([1, 2, 3, 4, 5, 6])
  245. .nwise(3)
  246. .subscribe { print($0) }
  247. ```
  248. ```
  249. next([1, 2, 3])
  250. next([2, 3, 4])
  251. next([3, 4, 5])
  252. next([4, 5, 6])
  253. completed
  254. ```
  255. #### retry
  256. Repeats the source observable sequence using given behavior in case of an error or until it successfully terminated.
  257. There are four behaviors with various predicate and delay options: `immediate`, `delayed`, `exponentialDelayed` and
  258. `customTimerDelayed`.
  259. ```swift
  260. // in case of an error initial delay will be 1 second,
  261. // every next delay will be doubled
  262. // delay formula is: initial * pow(1 + multiplier, Double(currentAttempt - 1)), so multiplier 1.0 means, delay will doubled
  263. _ = sampleObservable.retry(.exponentialDelayed(maxCount: 3, initial: 1.0, multiplier: 1.0), scheduler: delayScheduler)
  264. .subscribe(onNext: { event in
  265. print("Receive event: \(event)")
  266. }, onError: { error in
  267. print("Receive error: \(error)")
  268. })
  269. ```
  270. ```
  271. Receive event: First
  272. Receive event: Second
  273. Receive event: First
  274. Receive event: Second
  275. Receive event: First
  276. Receive event: Second
  277. Receive error: fatalError
  278. ```
  279. #### repeatWithBehavior
  280. Repeats the source observable sequence using given behavior when it completes. This operator takes the same parameters as the [retry](#retry) operator.
  281. There are four behaviors with various predicate and delay options: `immediate`, `delayed`, `exponentialDelayed` and `customTimerDelayed`.
  282. ```swift
  283. // when the sequence completes initial delay will be 1 second,
  284. // every next delay will be doubled
  285. // delay formula is: initial * pow(1 + multiplier, Double(currentAttempt - 1)), so multiplier 1.0 means, delay will doubled
  286. _ = completingObservable.repeatWithBehavior(.exponentialDelayed(maxCount: 3, initial: 1.0, multiplier: 1.2), scheduler: delayScheduler)
  287. .subscribe(onNext: { event in
  288. print("Receive event: \(event)")
  289. })
  290. ```
  291. ```
  292. Receive event: First
  293. Receive event: Second
  294. Receive event: First
  295. Receive event: Second
  296. Receive event: First
  297. Receive event: Second
  298. ```
  299. #### catchErrorJustComplete
  300. Completes a sequence when an error occurs, dismissing the error condition
  301. ```swift
  302. let _ = sampleObservable
  303. .do(onError: { print("Source observable emitted error \($0), ignoring it") })
  304. .catchErrorJustComplete()
  305. .subscribe {
  306. print ("\($0)")
  307. }
  308. ```
  309. ```
  310. next(First)
  311. next(Second)
  312. Source observable emitted error fatalError, ignoring it
  313. completed
  314. ```
  315. #### pausable
  316. Pauses the elements of the source observable sequence unless the latest element from the second observable sequence is `true`.
  317. ```swift
  318. let observable = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
  319. let trueAtThreeSeconds = Observable<Int>.timer(3, scheduler: MainScheduler.instance).map { _ in true }
  320. let falseAtFiveSeconds = Observable<Int>.timer(5, scheduler: MainScheduler.instance).map { _ in false }
  321. let pauser = Observable.of(trueAtThreeSeconds, falseAtFiveSeconds).merge()
  322. let pausedObservable = observable.pausable(pauser)
  323. let _ = pausedObservable
  324. .subscribe { print($0) }
  325. ```
  326. ```
  327. next(2)
  328. next(3)
  329. ```
  330. More examples are available in the project's Playground.
  331. #### pausableBuffered
  332. Pauses the elements of the source observable sequence unless the latest element from the second observable sequence is `true`. Elements emitted by the source observable are buffered (with a configurable limit) and "flushed" (re-emitted) when the observable resumes.
  333. Examples are available in the project's Playground.
  334. #### apply
  335. Apply provides a unified mechanism for applying transformations on Observable
  336. sequences, without having to extend ObservableType or repeating your
  337. transformations. For additional rationale for this see
  338. [discussion on github](https://github.com/RxSwiftCommunity/RxSwiftExt/issues/73)
  339. ```swift
  340. // An ordinary function that applies some operators to its argument, and returns the resulting Observable
  341. func requestPolicy(_ request: Observable<Void>) -> Observable<Response> {
  342. return request.retry(maxAttempts)
  343. .do(onNext: sideEffect)
  344. .map { Response.success }
  345. .catchError { error in Observable.just(parseRequestError(error: error)) }
  346. // We can apply the function in the apply operator, which preserves the chaining style of invoking Rx operators
  347. let resilientRequest = request.apply(requestPolicy)
  348. ```
  349. #### filterMap
  350. A common pattern in Rx is to filter out some values, then map the remaining ones to something else. `filterMap` allows you to do this in one step:
  351. ```swift
  352. // keep only even numbers and double them
  353. Observable.of(1,2,3,4,5,6)
  354. .filterMap { number in
  355. (number % 2 == 0) ? .ignore : .map(number * 2)
  356. }
  357. ```
  358. The sequence above keeps even numbers 2, 4, 6 and produces the sequence 4, 8, 12.
  359. #### errors, elements
  360. These operators only apply to observable sequences that have been materialized with the `materialize()` operator (from RxSwift core). `errors` returns a sequence of filtered error events, ommitting elements. `elements` returns a sequence of filtered element events, ommitting errors.
  361. ```swift
  362. let imageResult = _chooseImageButtonPressed.asObservable()
  363. .flatMap { imageReceiver.image.materialize() }
  364. .share()
  365. let image = imageResult
  366. .elements()
  367. .asDriver(onErrorDriveWith: .never())
  368. let errorMessage = imageResult
  369. .errors()
  370. .map(mapErrorMessages)
  371. .unwrap()
  372. .asDriver(onErrorDriveWith: .never())
  373. ```
  374. #### fromAsync
  375. Turns simple asynchronous completion handlers into observable sequences. Suitable for use with existing asynchronous services which call a completion handler with only one parameter. Emits the result produced by the completion handler then completes.
  376. ```swift
  377. func someAsynchronousService(arg1: String, arg2: Int, completionHandler:(String) -> Void) {
  378. // a service that asynchronously calls
  379. // the given completionHandler
  380. }
  381. let observableService = Observable
  382. .fromAsync(someAsynchronousService)
  383. observableService("Foo", 0)
  384. .subscribe(onNext: { (result) in
  385. print(result)
  386. })
  387. .disposed(by: disposeBag)
  388. ```
  389. #### zip(with:)
  390. Convenience version of `Observable.zip(_:)`. Merges the specified observable sequences into one observable sequence by using the selector function whenever all
  391. of the observable sequences have produced an element at a corresponding index.
  392. ```swift
  393. let first = Observable.from(numbers)
  394. let second = Observable.from(strings)
  395. first.zip(with: second) { i, s in
  396. s + String(i)
  397. }.subscribe(onNext: { (result) in
  398. print(result)
  399. })
  400. ```
  401. ```
  402. next("a1")
  403. next("b2")
  404. next("c3")
  405. ```
  406. #### merge(with:)
  407. Convenience version of `Observable.merge(_:)`. Merges elements from the observable sequence with those of a different observable sequences into a single observable sequence.
  408. ```swift
  409. let oddStream = Observable.of(1, 3, 5)
  410. let evenStream = Observable.of(2, 4, 6)
  411. let otherStream = Observable.of(1, 5, 6)
  412. oddStream.merge(with: evenStream, otherStream)
  413. .subscribe(onNext: { result in
  414. print(result)
  415. })
  416. ```
  417. ```
  418. 1 2 1 3 4 5 5 6 6
  419. ```
  420. #### ofType
  421. The ofType operator filters the elements of an observable sequence, if that is an instance of the supplied type.
  422. ```swift
  423. Observable.of(NSNumber(value: 1),
  424. NSDecimalNumber(string: "2"),
  425. NSNumber(value: 3),
  426. NSNumber(value: 4),
  427. NSDecimalNumber(string: "5"),
  428. NSNumber(value: 6))
  429. .ofType(NSDecimalNumber.self)
  430. .subscribe { print($0) }
  431. ```
  432. ```
  433. next(2)
  434. next(5)
  435. completed
  436. ```
  437. This example emits 2, 5 (`NSDecimalNumber` Type).
  438. #### [count](http://reactivex.io/documentation/operators/count.html)
  439. Emits the number of items emitted by an Observable once it terminates with no errors. If a predicate is given, only elements matching the predicate will be counted.
  440. ```swift
  441. Observable.from([1, 2, 3, 4, 5, 6])
  442. .count { $0 % 2 == 0 }
  443. .subscribe()
  444. ```
  445. ```
  446. next(3)
  447. completed
  448. ```
  449. #### partition
  450. Partition a stream into two separate streams of elements that match, and don't match, the provided predicate.
  451. ```swift
  452. let numbers = Observable
  453. .of(1, 2, 3, 4, 5, 6)
  454. let (evens, odds) = numbers.partition { $0 % 2 == 0 }
  455. _ = evens.debug("even").subscribe() // emits 2, 4, 6
  456. _ = odds.debug("odds").subscribe() // emits 1, 3, 5
  457. ```
  458. #### bufferWithTrigger
  459. Collects the elements of the source observable, and emits them as an array when the trigger emits.
  460. ```swift
  461. let observable = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
  462. let signalAtThreeSeconds = Observable<Int>.timer(3, scheduler: MainScheduler.instance).map { _ in () }
  463. let signalAtFiveSeconds = Observable<Int>.timer(5, scheduler: MainScheduler.instance).map { _ in () }
  464. let trigger = Observable.of(signalAtThreeSeconds, signalAtFiveSeconds).merge()
  465. let buffered = observable.bufferWithTrigger(trigger)
  466. buffered.subscribe { print($0) }
  467. // prints next([0, 1, 2]) @ 3, next([3, 4]) @ 5
  468. ```
  469. A live demonstration is available in the Playground.
  470. Reactive Extensions details
  471. ===========
  472. #### UIViewPropertyAnimator.animate
  473. The `animate(afterDelay:)` operator provides a Completable that triggers the animation upon subscription and completes when the animation ends.
  474. ```swift
  475. button.rx.tap
  476. .flatMap {
  477. animator1.rx.animate()
  478. .andThen(animator2.rx.animate(afterDelay: 0.15))
  479. .andThen(animator3.rx.animate(afterDelay: 0.1))
  480. }
  481. ```
  482. #### UIViewPropertyAnimator.fractionComplete
  483. The `fractionComplete` binder provides a reactive way to bind to `UIViewPropertyAnimator.fractionComplete`.
  484. ```swift
  485. slider.rx.value.map(CGFloat.init)
  486. .bind(to: animator.rx.fractionComplete)
  487. ```
  488. #### UIScrollView.reachedBottom
  489. `reachedBottom` provides a sequence that emits every time the `UIScrollView` is scrolled to the bottom, with an optional offset.
  490. ```swift
  491. tableView.rx.reachedBottom(offset: 40)
  492. .subscribe { print("Reached bottom") }
  493. ```
  494. ## License
  495. This library belongs to _RxSwift Community_.
  496. RxSwiftExt is available under the MIT license. See the LICENSE file for more info.