RxSwift Traits
2 min readApr 17, 2020
- Traits are observables with a narrow set of behaviors.
- Traits are simply a wrapper struct with a single read-only Observable sequence property.
Why Traits?
- Help communicate and ensure sequence properties.
- They are specialized in what you want to do. (Target more specific use-cases)
- Highly Expressive
- Communicates developer’s intention
- Provide syntactical sugar.
Note: Traits are entirely optional. You are free to use raw observables but I don’t find any reason to not use it.
Three Types of RxSwift Traits
Single
- Emits exactly one element, or an error. (Success or Error)
- While using Single you need to make sure one thing that it emits only a single element. It could result in the following error: Sequence contains more than one element.
- Common Usages -DB Fetch Operations, Network Requests
Output for above code -
Value is ["designation": "iOS Developer", "name": "John Doe"]
Disposed trait resources
Completable
- Emits an event case is “.completed” or “.error”
- Emits zero elements. (No data)
- Completable is used where we don’t care about the element result (data) but care about the fact that operation is completed.
- Common Usage -Updating a Cache.
Output for above code -
Completed Event
Disposed trait resources
Maybe
- Emits an event case is “.success” or “.completed” or “.error”
- Emits an element.
- Maybe can be used in the use-case where it doesn’t necessarily have to emit an element.
- It can either emit a single element, complete without emitting an element or emit an error.
- Common Usage -Fetching Data from Cache.
Output for above code -
Value is Number is greater than 5
Disposed trait resources
Thank you. I hope this helps!