Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create a reloading system with ReactiveCocoa
//
// SignalProducerReloaderType.swift
// Buienradar
//
// Created by Antoine van der Lee on 07/03/16.
// Copyright © 2016 Triple. All rights reserved.
//
import ReactiveCocoa
import CocoaLumberjack
typealias SignalProducerReloaderTypeReloadActionBlock = (() -> Void)
protocol SignalProducerReloaderType {
var reloadAction:SignalProducerReloaderTypeReloadActionBlock? { get set }
func signalProducerStarted()
func signalProducerCompleted()
}
/// Make methods optional
extension SignalProducerReloaderType {
func signalProducerStarted(){}
func signalProducerCompleted(){}
}
extension SignalProducerType {
func attachToSignalProducerReloader(reloader:SignalProducerReloaderType, reloadAction: SignalProducerReloaderTypeReloadActionBlock) -> SignalProducer<Value, Error> {
var reloader = reloader
let newProducer = producer.onStarted {
reloader.signalProducerStarted()
}.onCompleted {
reloader.signalProducerCompleted()
}
reloader.reloadAction = reloadAction
return newProducer
}
}
final class ForegroundReloader : SignalProducerReloaderType {
/// Used to check if view is vissible
var active: Bool = true // default = true
var reloadAction:SignalProducerReloaderTypeReloadActionBlock?
private let secondsInterval:NSTimeInterval
private var startDate:NSDate?
private let logLevel:DDLogLevel = .Warning
/**
Reloads the attached signal producer after a given period passed
- Parameter secondsInterval: the time to be passed when a new reload should be triggered
*/
init(secondsInterval:NSTimeInterval){
DDLogInfo("Init foreground reloader!", level: logLevel)
self.secondsInterval = secondsInterval
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ForegroundReloader.onForeground), name: UIApplicationDidBecomeActiveNotification, object: nil)
}
deinit {
DDLogInfo("Deinit foreground reloader!", level: logLevel)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
@objc private func onForeground(){
guard let reloadAction = reloadAction where active else { return }
guard let startDate = startDate where NSDate().timeIntervalSinceDate(startDate) > secondsInterval else {
DDLogInfo("Wont reload, not enough time passed!", level: logLevel)
return
}
DDLogInfo("Reloading from background!", level: logLevel)
reloadAction()
}
func signalProducerStarted(){
startDate = NSDate()
}
func reset(){
reloadAction = nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.