Skip to content

Instantly share code, notes, and snippets.

@ha1f
Last active May 25, 2018 03:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ha1f/6d3543e78836e8a1f428909392efd274 to your computer and use it in GitHub Desktop.
Save ha1f/6d3543e78836e8a1f428909392efd274 to your computer and use it in GitHub Desktop.
An Observable emits item only if _current == timeToLucky. Useful for testing.
//
// 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