티스토리 뷰
Single
success 또는 error 이벤트를 한 번만 방출될 수 있다.
var disposeBag = DisposeBag()
enum TraitsError: Error {
case single
case maybe
case completable
}
print("-------Single1-------") // 성공시
Single<Result<String, TraitsError>>.just(.success("✅"))
.subscribe(onSuccess: {
print($0)
}, onFailure: { _ in
print("error")
}, onDisposed: {
print("disposed")
})
.disposed(by: disposeBag)
print("-------Single2-------") // 실패시
Observable<Result<String, TraitsError>>.just(.failure(.single))
.asSingle()
.subscribe(onSuccess: {
print("success: \($0)")
}, onFailure: {
print("error: \($0.localizedDescription)")
}, onDisposed: {
print("disposed")
})
.disposed(by: disposeBag)
Single 를 이용한 decode 예제
print("------single------")
struct SomeJSON: Decodable {
let name: String
}
enum JSONError: Error {
case decodingError
}
let json1 = """
{"name":"hello"}
"""
func decode(json: String) -> Single<SomeJSON> {
Single<SomeJSON>.create { observer in
let disposable = Disposables.create()
guard let data = json.data(using: .utf8),
let json = try? JSONDecoder().decode(SomeJSON.self, from: data) else {
observer(.failure(JSONError.decodingError))
return disposable
}
observer(.success(json))
return disposable
}
}
decode(json: json1)
.subscribe{
switch $0 {
case .success(let json):
print(json.name)
case .failure(let error):
print(error)
}
}
.disposed(by: disposeBag)
------single------
hello
Completable
comleted 이벤트 또는 error 이벤트를 방출될 수 있다.
print("-------Completable-------")
Completable.create { completable in
completable(.completed)
return Disposables.create()
}
.subscribe(onCompleted: {
print("completed")
}, onError: {
print("error: \($0.localizedDescription)")
}, onDisposed: {
print("disposed")
})
.disposed(by: disposeBag)
-------Completable-------
completed
disposed
Maybe
success, completed , error 모두 방출될 수 있다.
print("-------Maybe1-------")
Maybe<Result<String, TraitsError>>.just(.success("✅"))
.subscribe(onSuccess: {
print("success: \($0)")
}, onError: {
print("error: \($0.localizedDescription)")
}, onCompleted: {
print("completed")
}, onDisposed: {
print("disposed")
})
.disposed(by: disposeBag)
-------Maybe1-------
success: success("✅")
disposed
Reference
'IOS > RxSwift' 카테고리의 다른 글
[RxSwift] Subject 알아보기 (0) | 2022.04.19 |
---|---|
RxSwift 개념 (0) | 2022.04.13 |
[RxSwift] Observable 알아보기 (0) | 2022.04.12 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- nginx
- 도커
- 네트워크
- SWIFT
- 엘라스틱서치
- python
- 리눅스
- spark
- 로그
- WEB
- linux
- network
- ElasticSearch
- BigData
- logstash
- docker
- ios
- pytest
- MYSQL
- SQL
- flask
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함