Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RxArray - A basic Reactive RxSwift array
import Foundation
import RxSwift
struct RxArray<T: Hashable> {
private let storage: BehaviorRelay<[T]>
private let lock = NSRecursiveLock()
var items: Observable<[T]> {
return storage.asObservable()
}
var count: Observable<Int> {
return storage.map { $0.count }
}
init(elements: [T] = []) {
storage = BehaviorRelay(value: elements)
}
func append(_ element: T) {
lock.lock(); defer { lock.unlock() }
storage.accept(storage.value + [element])
}
func removeFirst(_ element: T) {
lock.lock(); defer { lock.unlock() }
var items = storage.value
guard let idx = items.index(of: element) else { return }
items.remove(at: idx)
storage.accept(items)
}
func removeAll(_ element: T) {
lock.lock(); defer { lock.unlock() }
storage.accept(storage.value.filter { $0 != element })
}
}
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.