Skip to content

Instantly share code, notes, and snippets.

@fhefh2015
Created July 15, 2021 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fhefh2015/c0bb4c82d9a3c32368ee9bcb7fb6763b to your computer and use it in GitHub Desktop.
Save fhefh2015/c0bb4c82d9a3c32368ee9bcb7fb6763b to your computer and use it in GitHub Desktop.
RxSwift:Single实例:读取文件
func loadText(from name: String) -> Single<String> {
enum FileReadError: Error {
case fileNotFount
case unreadable
case encodingFailed
}
return Single.create {
single in
let disposable = Disposables.create()
guard let path = Bundle.main.path(forResource: name, ofType: "txt") else {
single(.failure(FileReadError.fileNotFount))
return disposable
}
guard let data = FileManager.default.contents(atPath: path) else {
single(.failure(FileReadError.unreadable))
return disposable
}
guard let contents = String(data: data, encoding: .utf8) else {
single(.failure(FileReadError.encodingFailed))
return disposable
}
single(.success(contents))
return disposable
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment