Skip to content
This repository has been archived by the owner on Mar 6, 2018. It is now read-only.

Commit

Permalink
Observable create pattern for async calls
Browse files Browse the repository at this point in the history
  • Loading branch information
ivanbruel committed May 25, 2016
1 parent 3a67656 commit 21d1d4d
Showing 1 changed file with 5 additions and 55 deletions.
60 changes: 5 additions & 55 deletions Source/RxPermission.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,61 +25,11 @@ import Permission
import RxSwift

public extension Permission {
/// Reactive wrapper for `Permission` instance.
public var rx_permission: Observable<PermissionStatus> {
return rx_permissionInstance.asObservable()
}
}

// MARK: - Permission

extension Permission: AssociatedObject {
private var rx_permissionInstance: PublishSubject<PermissionStatus> {
get {
var permission: PublishSubject<PermissionStatus>!

doLocked {
if let lookup = self.associatedObject(&.permission) as? PublishSubject<PermissionStatus> {
permission = lookup
} else {
permission = PublishSubject<PermissionStatus>()
self.request { permission.onNext($0) }
self.rx_permissionInstance = permission
}
}

return permission
}

set {
doLocked {
self.associatedObject(&.permission, object: newValue)
}
}
}

private func doLocked(closure: () -> Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
closure()
public var rx_permission: Observable<PermissionStatus> {
return Observable.create { (observer) in
self.request { observer.onNext($0) }
return AnonymousDisposable { observer.onCompleted() }
}
}

// MARK: - AssociatedObject

private protocol AssociatedObject {}

private extension AssociatedObject where Self: AnyObject {
func associatedObject(inout key: String) -> AnyObject! {
return objc_getAssociatedObject(self, &key)
}

func associatedObject(inout key: String, object: AnyObject) {
objc_setAssociatedObject(self, &key, object, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}

// MARK: - String

private extension String {
static var permission = "rx_permissionInstance"
}
}

0 comments on commit 21d1d4d

Please sign in to comment.