RxSwift
RxSwift is a library for composing asynchronous and event-based code by
using observable sequences and functional style operators, allowing for
parameterized execution via schedulers. – It is a reactive programming framework for Swift.
Why do we use RxSwift?
-
RxSwift makes it easy to “develop dynamic applications” that respond to changes in data and respond to user events.
-
It is a multi-platform standard, and its difficult-to-handle asynchronous code in Swift becomes much easier in Rx-Swift.
-
You can react to changes on different threads. You do this with a lot less code, less complexity, less bugs.
What is DisposeBag?
-
This is a virtual bag of Observer objects
-
Which are disposed of when the parent object is deallocated.
-
Thread safe bag that disposes added disposables on deinit.
-
This returns ARC (RAII) like resource management to RxSwift.
-
DisposeBag is exactly what it says it is, a bag (or collection) of disposables.
-
When the view controller is deallocated, its variables (including the bag) are deallocated.
-
When the disposeBag is deallocated, its deinit function calls dispose on all of the disposables it contains.
Building blocks of Rx
1. Observable: It is a sequence of events or values that are emitted over a
time.
- It is a part of Reactive Extensions(Rx) framework
- It represents a stream of data that can emit three types of events.
i. Next Event
ii. Error Event
iii. Completed Event - Next Event(carrying data values): This event carries a value and represents
the data or value emitted by the observable at a specific point in time. - Observables can emit any number of next events.
- Error Event(indicating a failure): This event signifies that an error has occurred during the execution of the observable sequence.
- Once an error event is emitted, observables can no longer emit any more events.
- Completed Event:(end of the sequence) This event indicates that the
observable sequence has been successfully completed. And no more events are emitted.
2. Observer: The observer is a subscriber of the events that are emitted by an observable.
- It defines how to react to next, error and completed events from the
observable.
3. Subscription: It represents the connection between the observer and the observable.
- Subscription can be managed to control the lifecycle connections.
4. Operators: Operators are methods or functions provided by the Rx to transform, filter, combine or manipulate observables and their emitted values.
- Operators allow complex data operations in a declarative and composable manner.
5. Schedulers: schedulers control when the events are emitted and received.
- Schedulers allow you to control the execution context of the observable
sequence and their associated operations. - RxSwift provides several built-in schedulers used to manage concurrency.
- MainScheduler
Used to perform on main thread, it is used to interact with user
interface like updating the UI elements - Concurrent Dispatch Queue Scheduler
i. Used to specify a custom background queue.
ii. It is useful for offloading tasks on the main thread to avoid the blocking of UI. - Serial Dispatch Queue Scheduler
iii. Same as concurrentDispatchQueueScheduler
iv. Work is performed in a serial manner one task at a time.
v. Which can be useful in avoiding race conditions. - Immediate Scheduler
vi. Executes work synchronously on the current thread.
6.Subjects: Subjects are both observers and observables, They can emit events (next,
error, completed) and subscribe to other observables.
– They allow you to inject the values into an observable sequence.
- PublishSubject: emits value to current subscribers but does not reply to
previous values to new subscribers
Ex: – let subject = PublishSubject<String>()
subject.onNext(“Event 1”)
subject.subscribe { event in
print(event)
}
subject.onNext(“Event 2”)
Output: Event 2 (current subscriber value) - BehaviorSubject: emits the most recent values to the new subscribers
Ex:- let behaviorSubject = BehaviorSubject<String>(value: “Initial Value”)
behaviorSubject.onNext(“Updated Value”)
behaviorSubject.subscribe { event in
print(event)
}
behaviorSubject.onNext(“New Value”)
OutPut: Updated Value,New Value - ReplaySubject: Initialised with buffer size and will maintain a buffer of elements up to the size and replay it to new subscribers.
- AsyncSubject: Start with empty and only emit the last item it receives before it’s completed to subscribers.
Conclusion:
RxSwift is a valuable tool for iOS developers seeking to create responsive, maintainable, and scalable applications by leveraging the power of reactive programming. While it may require an initial investment in learning, the benefits it offers in terms of code clarity and handling complex asynchronous scenarios make it a worthwhile choice for many iOS projects.
Contact info@japptech.com to achieve the best-of-class application for your new venture or product. We promise to keep you ahead of your competitors.