RxSwift Traits

Dive into Single, Completable and Maybe

Aaina jain
Sep 3, 2018 · 4 min read

Traits are just a read-only Observable sequence property wrapped into a Struct. Traits are entirely optional. You are free to use raw Observable sequences everywhere in your program as all core RxSwift/RxCocoa APIs support them.

* Single<T>:

A Single is something like an Observable that instead of emitting a series of values, is guaranteed to be return either a value or an error.

  • Emits exactly one element, or an error.
  • Doesn’t share side effects.

For this reason, instead of subscribing to Single with 3 methods you subscribe with only 2 methods.


public enum SingleEvent<Element> {
/// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`)case success(Element)/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)case error(Swift.Error)}
  • It could be used for network requests which is performed once and return a value or an error means you don’t expect it to return additional values over time.
  • For DB fetch data operation.
  • A Single can be used to model any case where you only care for a single element, and not for an infinite stream of elements.
  • Once image is loaded, then you want to perform some operation.

A raw Observable sequence can be converted to Single using .asSingle()

Note: While using Single you need to make sure one thing that it emit only single element. It could result in following error: Sequence contains more than one element.

* Completable:

A Completable represent a Observable that can only complete or emit an error. It’s equivalent to Observable<Void> that can’t emit elements.

  • Emits zero elements.
  • Emits a completion event, or an error.
  • Doesn’t share side effects.
Completable Marble diagram
public enum CompletableEvent {/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)case error(Swift.Error)/// Sequence completed successfully.case completed}
  • When an operation has completed, but you don’t care about a element resulted by that completion.
  • Updating a Cache for instance,
  • UPDATE/PUT network call that resulted with success indication only.
  • You have to perform operation when network connection is re-established.
func cacheLocally() -> Completable {
return Completable.create { completable in
// Store some data locally
...
...

guard success else {
completable(.error(CacheError.failedCaching))
return Disposables.create {}
}

completable(.completed)
return Disposables.create {}
}
}

A raw Observable sequence can be converted to Completable using .asCompletable() or an completable can be completed with Completable.empty()

* Maybe<T>:

Maybe is the combination of Completable and Single. Maybe is useful when we want to write that an Observable might not have a value and will just complete. It can either emit a single element, complete without emitting an element, or emit an error.

  • Emits either a completed event, a single element or an error.
  • Doesn’t share side effects.
Maybe RxMarble diagram
public enum MaybeEvent<Element> {/// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`)case success(Element)/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)case error(Swift.Error)/// Sequence completed successfully.case completed}
  • While fetching data from the cache, we won’t necessarily have a value in the cache, so in this case, we will complete, o.w. we will get onSuccess with the value from the cache.

Creating a Maybe:

func generateString() -> Maybe<String> {
return Maybe<String>.create { maybe in
maybe(.success("RxSwift"))

// OR

maybe(.completed)

// OR

maybe(.error(error))

return Disposables.create {}
}
}

A raw Observable sequence can be converted to Maybe using .asMaybe()

References:

https://github.com/ReactiveX/RxSwift/blob/master/Documentation/Traits.md

Recommended Articles:

RxSwift Combining Operators

RxSwift Transforming Operators


You can catch me at:

Linkedin: Aaina Jain

Twitter: __aainajain

If you have any suggestions for the next post write to me at aainajain100@gmail.com.

Swift India

Swift Developer Community in India 🇮🇳

Aaina jain

Written by

Product Engineer📱at Go-Jek Tech, Organizer & Editor at Swift India

Swift India

Swift Developer Community in India 🇮🇳

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade