1
1
mirror of https://github.com/qvacua/vimr.git synced 2024-12-28 08:13:17 +03:00
vimr/NvimView/MinimalNvimViewDemo/RxSwiftCommons.swift
2019-03-26 20:04:18 +01:00

85 lines
1.7 KiB
Swift

/**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Foundation
import RxSwift
extension PrimitiveSequence
where Element == Never, TraitType == CompletableTrait {
func wait(
onCompleted: (() -> Void)? = nil,
onError: ((Error) -> Void)? = nil
) throws {
var trigger = false
var err: Error? = nil
let condition = NSCondition()
condition.lock()
defer { condition.unlock() }
let disposable = self.subscribe(onCompleted: {
onCompleted?()
condition.lock()
defer { condition.unlock() }
trigger = true
condition.broadcast()
}, onError: { error in
onError?(error)
err = error
condition.lock()
defer { condition.unlock() }
trigger = true
condition.broadcast()
})
while !trigger { condition.wait(until: Date(timeIntervalSinceNow: 5)) }
disposable.dispose()
if let e = err {
throw e
}
}
}
extension PrimitiveSequence where TraitType == SingleTrait {
func syncValue() -> Element? {
var trigger = false
var value: Element?
let condition = NSCondition()
condition.lock()
defer { condition.unlock() }
let disposable = self.subscribe(onSuccess: { result in
value = result
condition.lock()
defer { condition.unlock() }
trigger = true
condition.broadcast()
}, onError: { error in
condition.lock()
defer { condition.unlock() }
trigger = true
condition.broadcast()
})
while !trigger { condition.wait(until: Date(timeIntervalSinceNow: 5)) }
disposable.dispose()
return value
}
func asCompletable() -> Completable {
return self.asObservable().ignoreElements()
}
}