Created
February 16, 2020 20:21
-
-
Save yzhong52/34f4111eda3b0a86c5527c0d0fab38c2 to your computer and use it in GitHub Desktop.
Building a Client App From Scratch - NewsManager
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
import Foundation | |
import RxSwift | |
import RxCocoa | |
class NewsManager { | |
typealias NewsLoadState = LoadState<ArticlesResponse> | |
enum LoadError: Error { | |
case unknownError | |
} | |
private let client = NewsClient() | |
private let timer = Observable<Int>.timer( | |
RxTimeInterval.seconds(0), | |
period: RxTimeInterval.seconds(120), | |
scheduler: ConcurrentDispatchQueueScheduler(qos: .background)) | |
func news() -> Driver<NewsLoadState> { | |
return timer.flatMapLatest { [client] (count) -> Observable<NewsLoadState> in | |
let pending: NewsLoadState = (count == 0) ? .loading : .updating | |
let loaded: Observable<NewsLoadState> = client.headlines() | |
.map({ .loaded(response: $0) }) | |
.catchError({ Single.just(.failed(error: $0)) }) | |
.asObservable() | |
return Observable.merge([Observable.just(pending), loaded]) | |
}.asDriver(onErrorJustReturn: .failed(error: LoadError.unknownError)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment