forked from ReactiveX/RxSwift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RunLoopLock.swift
103 lines (94 loc) · 2.99 KB
/
RunLoopLock.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// RunLoopLock.swift
// RxBlocking
//
// Created by Krunoslav Zaher on 11/5/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import CoreFoundation
import Foundation
import RxSwift
#if os(Linux) || os(Android)
#if compiler(>=5.0)
let runLoopMode: RunLoop.Mode = .default
#else
let runLoopMode: RunLoopMode = .defaultRunLoopMode
#endif
let runLoopModeRaw: CFString = unsafeBitCast(runLoopMode.rawValue._bridgeToObjectiveC(), to: CFString.self)
#else
let runLoopMode: CFRunLoopMode = CFRunLoopMode.defaultMode
let runLoopModeRaw = runLoopMode.rawValue
#endif
final class RunLoopLock {
let _currentRunLoop: CFRunLoop
let _calledRun = AtomicInt(0)
let _calledStop = AtomicInt(0)
var _timeout: TimeInterval?
init(timeout: TimeInterval?) {
self._timeout = timeout
self._currentRunLoop = CFRunLoopGetCurrent()
}
func dispatch(_ action: @escaping () -> Void) {
CFRunLoopPerformBlock(self._currentRunLoop, runLoopModeRaw) {
if CurrentThreadScheduler.isScheduleRequired {
_ = CurrentThreadScheduler.instance.schedule(()) { _ in
action()
return Disposables.create()
}
}
else {
action()
}
}
CFRunLoopWakeUp(self._currentRunLoop)
}
func stop() {
if decrement(self._calledStop) > 1 {
return
}
CFRunLoopPerformBlock(self._currentRunLoop, runLoopModeRaw) {
CFRunLoopStop(self._currentRunLoop)
}
CFRunLoopWakeUp(self._currentRunLoop)
}
func run() throws {
if increment(self._calledRun) != 0 {
fatalError("Run can be only called once")
}
if let timeout = self._timeout {
#if os(Linux) || os(Android)
switch Int(CFRunLoopRunInMode(runLoopModeRaw, timeout, false)) {
case kCFRunLoopRunFinished:
return
case kCFRunLoopRunHandledSource:
return
case kCFRunLoopRunStopped:
return
case kCFRunLoopRunTimedOut:
throw RxError.timeout
default:
fatalError("This failed because `CFRunLoopRunResult` wasn't bridged to Swift.")
}
#elseif os(Android)
fatalError("This failed because `CFRunLoopRunResult` wasn't bridged to Swift.")
return
#else
switch CFRunLoopRunInMode(runLoopMode, timeout, false) {
case .finished:
return
case .handledSource:
return
case .stopped:
return
case .timedOut:
throw RxError.timeout
default:
return
}
#endif
}
else {
CFRunLoopRun()
}
}
}