Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
RxSwift note
  • Composable, Reusable
  • Declarative
  • Immutable


Fundamental part of RxSwift, Read-only

Create and subscribe Observable

let disposeBag = DisposeBag()

// Create
let observable = Observable.of(1, 3, 7)

// Subscribe
    .subscribe(onNext: { element in 
        print("Element:", element)
    }, onError: { error in 
        print("Error:", error)
    }, onCompleted: {
    }, onDisposed: {
    .disposed(by: disposeBag)

Other examples

let observable = Observable.of(1, 3, 7)
let observable = Observable.just(true)
let observable = Observable.from([1, 3, 7])
let observable = Observable.from(p[tion[1, 3, 7])
// never stop
let observable: Observable<Int> = .never()
// only completed
let observable: Observable<Int> = .empty()
// only error
let error = NSError(domain: "test", code: -1, userInfo: nil)
let observable: Observable<Int> = .error(error)

Custom Observable

// Custom Observable
let disposeBag = DisposeBag()
let myJust = { (element: String) -> Observable<String> in
    return Observable.create { observer in
        return Disposables.create()
    .subscribe { print($0) }
    .disposed(by: disposeBag)

Observable vs Driver

Driver automatically adds shareReplay(1)

// By Observable
var username = Observable<String>
validatedUsername = input.username
    .flatMapLatest { username in
        return validationService.validateUsername(username)
            .catchErrorJustReturn(.failed(message: "Error contacting server"))
    .share(replay: 1)
// By Driver
validatedUsername = input.username
    .flatMapLatest { username in
        return validationService.validateUsername(username)
            .asDriver(onErrorJustReturn: .failed(message: "Error contacting server"))
.catchErrorJustReturn(.Failed(message: "Error contacting server"))
// are squashed into single 

.asDriver(onErrorJustReturn: .Failed(message: "Error contacting server"))


Can act as both observable and as observer


  • PublishSubject: Starts empty and only emits new elements to subscribers.
  • BehaviorSubject: Starts with an initial value and replays it or the latest element to new subscribers.
  • ReplaySubject: Initialized with buffer size and will remain a buffer of elements up to that size and replay it to new subscribers.
  • AsyncSubject: Emits only the last next event in the sequence, and only where subject receives a completed event. This is a seldom used kind of subject.


Relay is wrappers around Subject, Accept and relay next events

  • PublishRelay
  • BehaviorRelay: Wraps a BehaviorSubject, preserves its current value as a state, and replays only the latest/initial value to new subscribers.

Learning resource

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment