Last active
August 17, 2016 09:27
-
-
Save yota345/2a64fba858a9a0fdab9f1022b4e0a6af to your computer and use it in GitHub Desktop.
RxCounter.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 秒数カウンターを実装。いまは実装内容を深く考えないでください。 | |
func myInterval(interval: NSTimeInterval) -> Observable<Int> { | |
return Observable.create { observer in | |
print("Subscribed") | |
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) | |
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue) | |
var next = 0 | |
dispatch_source_set_timer(timer, 0, UInt64(interval * Double(NSEC_PER_SEC)), 0) | |
let cancel = AnonymousDisposable { | |
print("Disposed") | |
dispatch_source_cancel(timer) | |
} | |
dispatch_source_set_event_handler(timer, { | |
if cancel.disposed { | |
return | |
} | |
observer.on(.Next(next)) | |
next += 1 | |
}) | |
dispatch_resume(timer) | |
return cancel | |
} | |
} | |
let counter = myInterval(0.1) | |
print("Started ----") | |
let subscription1 = counter | |
.subscribeNext { n in | |
print("First \(n)") | |
} | |
let subscription2 = counter | |
.subscribeNext { n in | |
print("Second \(n)") | |
} | |
NSThread.sleepForTimeInterval(0.5) | |
subscription1.dispose() | |
NSThread.sleepForTimeInterval(0.5) | |
subscription2.dispose() | |
print("Ended ----") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment