Created
July 15, 2021 08:31
-
-
Save fhefh2015/c0bb4c82d9a3c32368ee9bcb7fb6763b to your computer and use it in GitHub Desktop.
RxSwift:Single实例:读取文件
This file contains hidden or 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
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