Skip to content

Instantly share code, notes, and snippets.

@funmia
Created August 18, 2018 12:08
Show Gist options
  • Select an option

  • Save funmia/1fdd7ec547e3bbfa7e55aad3421df7c2 to your computer and use it in GitHub Desktop.

Select an option

Save funmia/1fdd7ec547e3bbfa7e55aad3421df7c2 to your computer and use it in GitHub Desktop.
RxSwift - Observables

Resources:

https://tylermcginnis.com/imperative-vs-declarative-programming/ http://reactivex.io http://reactivex.io/documentation/operators.html#tree https://github.com/ReactiveX/RxSwift https://forums.raywenderlich.com/t/playground-does-not-execute-on-first-chapter/41341/24

To fix 'No such module: RxSwift' error change the selected device to a simulator.

The foundation of the RX framework is to create and observe event sequences. It helps to create asynchronous programs that react to new data and process it in a sequential manner.

Observables:

The Observable class provides the ability to asynchronously produce a sequence of events that hold an immutable snapshot of data of type T. For example, it allows classes to subscribe for events emitted by another class over time.

An Observable can also be referred to as an observable sequence, sequence or a stream. Observables are asynchronous; they emit events over a period of time.

An Observer is something that receive events.

An Observable can emit 3 types of events;

  • A next event: This carries the latest data value, this is how observers receive values.

  • A completed event: This terminates the event sequence with a success. A completed event means that the Observable completed its lifecycle successfully and it won't emit any further events.

  • An error event: This means the Observable terminated with an error and it won't emit any further events.

Observable Operators

In Rx methods are called operators.

  • just - The just operator creates an observable sequence that contains just one element.
let observable = Observable<Int>.just(1)
  • of - This operator creates an observable sequence that can contain a variable number of elements.
let observable = Observable.of(1,2,3)
Subscribing:

This means to observe the events produced by an observable sequence. A subscriptions triggers an observable to begin emitting events until it emits an .error or .completed event and is terminated.

Disposing and terminating -

An observable automatically terminates when it emits an .error or .completed event. To manually terminate an Observable you can call .dispose() on it. RxSwift includes a DisposeBag type that can hold disposables. The DisposeBag will dispose each of the disposables when it is about to be deallocated. If a subscription is not added to a dispose bag, manually disposed or terminated after it is no longer needed, this will cause a memory leak.

let disposeBag = DisposeBag()

Observable.of("1","2","3")
  .subscribe {
    print($0)
  }
  .dispose(by: disposeBag)

  • create - This operator provides another way to specify all the events that an observable will emit to subscribers. It's parameter is an escaping closure with a parameter of type AnyObserver and it returns a Disposable. The AnyObserver type allows us to add values onto an observable sequence and these values are emitted to subscribers.
let disposeBag = DisposeBag()

Observable<String>.create { observer in
      observer.onNext("1")
      observer.onNext("2")
      observer.onCompleted()

      return Disposables.create()
}
.subscribe(
        onNext: { print($0) },
        onCompleted: { print("completed") },
        onDisposed: { print("disposed") }
    ).disposed(by: disposeBag)
  • debug - This operator allows you to print information about every event from an Observable sequence to the console.

Traits

A trait is a type of Observable that has a limited set of behaviours. The three kinds of traits in RxSwift are Single, Completable and Maybe. You can use traits to make the intent of your code clearer.

  • Single: A Single will emit either a .success(value) or .error event. A .success event is combination of .next and .completed. Use a single for operations that will either succeed with a value or fail such as a network request.

  • Completable: A Completable will either emit a .completed or an .error event. Use this when you don't care about the result of an operation but you care if it completed successfully or failed.

  • Maybe: Maybe is a combination of a Single and Completable. It can either emit a .success(value), .completed or .error.

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