RxSwift — Observables

The core concept of Rx

Priya Talreja
2 min readJan 27, 2020

Introduction

  • The heart of the RxSwift framework is based on observable which is also known as a sequence.
  • Observable is the sequence of data or events which can be subscribed and can be extended by applying different Rx operators like map, filter, flatMap, etc.
  • It can receive data asynchronously.
  • You can create an observable sequence of any Object that conforms to the Sequence protocol (A type that provides sequential, iterated access to its elements).

Implementing Observables

  • just is an observable sequence containing the single specified element.
  • of operator is used to create an observables array or an observable of individual type.
  • from operator creates an observable of individual type from an array of elements.

from and of observables are very different. of observable will function on an array but from observable will function on individual elements of the array rather than the whole array.

We have created observablesbut we need to subscribe to the observables. Anobservable won’t send events until it has a subscriber.

Implementing Subscriptions

The Subscribe is how you connect an observer to an Observable.

  • onNext This method is called whenever the Observable emits an item. This method takes as a parameter the item emitted by the Observable. When a value is added to an observable it will send the next event to its subscribers.
  • onError This method is called whenever an error event is emitted indicating that it has failed to generate the expected data or has encountered some other error. Further calls to onNext or onCompletedare not made. The method returns the details of the error. This will terminate the observable sequence.
  • onCompleted This method after observable has emitted all the events and sends a completed event to its subscribers. This method is not called if any error event has encountered.

Disposing and terminating

  • When we create a subscription it returns you a subscriber and that subscriber will always be listening or observing that particular observable sequence. So we need to make sure that we dispose of those subscribers.
  • A memory leak may occur if we don’t expose those subscribers.
  • You can add the subscription to a Disposebag which will cancel the subscription for you automatically.
  • dispose() is used to cancel the subscription manually and free resources.

Thank you. I hope this helps!

--

--