Skip to content

Instantly share code, notes, and snippets.

@GeekTree0101
Last active July 30, 2019 14:04
Show Gist options
  • Save GeekTree0101/e9b812255bd04a08ec5c1cd17d0c0659 to your computer and use it in GitHub Desktop.
Save GeekTree0101/e9b812255bd04a08ec5c1cd17d0c0659 to your computer and use it in GitHub Desktop.
Repository Example
import RxSwift
import RxCocoa
class Repository {
private let remoteDataSource: RemoteDataSource
private let localDataSource: LocalDataSource
private let errorRelay = PublishRelay<Error?>()
init(remote: RemoteDataSource, local: LocalDataSource) {
self.remoteDataSource = remote
self.localDataSource = local
}
public func getHistory() -> Observable<History?> {
return localDataSource.getHistory()
}
public func refreshHistory(id: Int) {
_ = remoteDataSource.getHistory(id)
.subscribe(onSuccess: { [weak self] history in
self?.localDataSource.setHistory(history)
}, onError: { [weak self] error in
self?.errorRelay.accept(error)
})
}
public func error() -> Observable<Error?> {
return errorRelay.asObservable()
}
}
class RemoteDataSource {
public func getHistory(_ id: Int) -> Single<History> {
// remote api
return Single.just(History(id: 1, title: "remote", isFollow: true))
}
}
class LocalDataSource {
private var historyStore: BehaviorRelay<History?> = .init(value: nil)
public func setHistory(_ history: History) {
historyStore.accept(history)
}
public func getHistory() -> Observable<History?> {
return historyStore.asObservable()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment