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.

42 lines
1.2 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. //
  2. // once.swift
  3. // RxSwiftExt
  4. //
  5. // Created by Florent Pillet on 12/04/16.
  6. // Copyright © 2016 RxSwift Community. All rights reserved.
  7. //
  8. import Foundation
  9. import RxSwift
  10. extension Observable {
  11. /**
  12. Returns an observable sequence that contains a single element. This element will be delivered to the first observer
  13. that subscribes. Further subscriptions to the same observable will get an empty sequence.
  14. In most cases, you want to use `Observable.just()`. This one is really for specific cases where you need to guarantee
  15. unique delivery of a value.
  16. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
  17. - parameter element: Single element in the resulting observable sequence.
  18. - returns: An observable sequence containing the single specified element delivered once.
  19. */
  20. public static func once(_ element: Element) -> Observable<Element> {
  21. let lock = NSRecursiveLock()
  22. var isDelivered = false
  23. return create { observer in
  24. lock.lock()
  25. if !isDelivered {
  26. observer.onNext(element)
  27. }
  28. isDelivered = true
  29. lock.unlock()
  30. observer.onCompleted()
  31. return Disposables.create()
  32. }
  33. }
  34. }