Last active
May 25, 2018 03:22
-
-
Save ha1f/6d3543e78836e8a1f428909392efd274 to your computer and use it in GitHub Desktop.
An Observable emits item only if _current == timeToLucky. Useful for testing.
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
// | |
// NthTimeLucky.swift | |
// | |
// Created by はるふ on 2018/05/24. | |
// Copyright © 2018年 ha1f. All rights reserved. | |
// | |
import Foundation | |
import RxSwift | |
extension ObservableType { | |
static func nthTimeLucky(_ item: E, timeToLucky: Int, errorItem: Error = NSError()) -> Observable<E> { | |
return NthTimeLucky(item, timeToLucky: timeToLucky, errorItem: errorItem).asObservable() | |
} | |
} | |
/// An Observable emits item only if _current == timeToLucky. | |
/// TBH, I want to inherit from Observable<E> | |
private class NthTimeLucky<E>: ObservableType { | |
/// item to emit on lucky time | |
let item: E | |
/// item to emit except lucky time | |
let errorItem: Error | |
let timeToLucky: Int | |
private var _current: Int = 1 | |
init(_ item: E, timeToLucky: Int, errorItem: Error) { | |
self.item = item | |
self.timeToLucky = timeToLucky | |
self.errorItem = errorItem | |
} | |
func subscribe<O>(_ observer: O) -> Disposable where O: ObserverType, E == O.E { | |
let disposable = Disposables.create() | |
defer { | |
_current += 1 | |
} | |
guard _current == timeToLucky else { | |
observer.onError(errorItem) | |
return disposable | |
} | |
observer.onNext(item) | |
return disposable | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment