Basic of RxSwift

![image.png](https://qiita-image-store.s3.amazonaws.com/0/279562/09724921-975d-159d-4a38-5ad8eea2c880.png)

>[ReactiveX](http://reactivex.io) (usually abbreviated to “Rx”) is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming

I am going to talk about **RxSwift** which is part of **Rx** in Swift Version. Basically, **RxSwift** is a framework for interacting with swift programming language and **RxCocoa** is a framework that helps make Cocoa APIs used in iOS and OS X easier to use with reactive techniques.

##Observable and Observer

Whenever people talk about **RxSwift** first thing in my mind is *Observable and Observer*.

- Observable: emits notifications of changes.
- Observer: subscribes to an Observable, in order to be notified when it has changed.

**Note**: We can have more than one Observer listening to an Observable. So when that Observable changes it will notify to all its Observers.

Here are some examples of Observable:

```swift
let helloObservable = Observable.just("Hello")

let arrayObservable = Observable.from(["H", "e", "l", "l", "o"]

let dictObservable = Observable.from([1:"Hello", 2: "RxSwift"])
```

And Here are some examples of Observer as well:

So we can subscribe to Observable by calling `subscribe(on:(Event<T>)->())`

```swift
let helloObservable = Observable.just("Hello")
let subscription = helloObservable.subscribe { event in 
   print(event)
}
```
The out put will be:

```
Output:
next("Hello")
completed
```

So **helloObservable** will send its contained value "Hello" to its subscription. it sends the event to the pass block. **subscription** variable called subscribe method which receive the event from its Observable.

In **RxSwift**, *Event* is just a enumeration type with 3 states:
- **.next(value: T)**: when value added to an Observable then it will send *next event* to its subscribers
- **.error(error: Error)**: if error happened, it sends *error event* and terminate the process
- **.completed**: when Observable ends normally, it sends *completed event* to its subscribers.

```swift
let arryObservable = Observable.from(["H", "e", "l", "l", "o"])
let subscription = arrayObservable.subscribe { event in 
   switch event {
      case .next (let value):
         print(value)
      case .error (let error):
         print(error)
      case .completed:
         print("completed")
   }
}
```
Output is going to be:

```
H
e 
l 
l 
o
completed
```

##DisposeBag
**DisposeBag** is a virtual bag of Observer objects which are disposed when their parent object is deallocated. it is deal with memory management. So if we want to cancel the subscription we can do it by just calling **dispose** on it. We can also add a subscription with the **DisposeBag** which will cancel automatically on **deinit** of the DisposeBag instance.

```swift
let bag = DisposeBag()

let helloObservable = Observable.just("Hello")
let subscription = helloObservable.subscribe { event in 
    print(event)
}
//adding a subscription to a DisposeBag
subscription.disposed(by: bag)
``` 
##Transforming 
Sometimes we want to transform, combine or filter the elements emitted by the Observable before the Observer receives them. Here are some basic operations of transformation:

**Map**
To transform elements emitted by Observable before they reach their Observers, you can use **map** operation. Imagine a transformation that multiplies each value of the sequence with 10 before emitting.

```swift
Observable<Int>.of(1, 2, 3, 4, 5).map { value in 
    return value * 10
   }.subscribe(onNext: {
        print($0)
})
```
The output will be:

```
10 20 30 40 50
```
<img width="819" alt="Screen Shot 2019-03-08 at 11.05.25 PM.png" src="https://qiita-image-store.s3.amazonaws.com/0/279562/588ccb3a-2d6a-d5b9-95c6-be1d3c4cc2e1.png">

**FlatMap**
Imagine that an Observable that consists of objects that are themselves Observable and we want to create a new sequence from those. This is where *FlatMap* comes into play. FlatMap emerges the results and emitting the results as its own Observable.

```swift
let observable1 = Observable<Int>.of(1,2)
let observable2 = Observable<Int>.of(1,2)

let observableOfobservable = Observable.of(observable1, observable2)
observableOfobservable.flatMap{ return $0 }.subscribe(onNext: {
   print($0)
})
``` 
The output will be:

```
1 2 1 2
```
![image.png](https://qiita-image-store.s3.amazonaws.com/0/279562/db33f291-051c-795d-3b6b-650bf3326cde.png)
**Scan**
Scan starts with initial seed value and is used to aggregate value just like reduce in swift.

```swift
Observable.of(1, 2, 3, 4, 5).scan(0) { seed, value in
    return seed + value 
}.subscribe(onNext: {
    print($0)
})
```
The output will be:

```
1 3 6 10 15
```
<img width="821" alt="Screen Shot 2019-03-08 at 11.29.48 PM.png" src="https://qiita-image-store.s3.amazonaws.com/0/279562/bab07c78-6628-d233-1e48-930c607bbd30.png">

**Filter**
The basic filter operation works similar to swift equivalent. I just define a condition that needs to be passed and if the condition fulfilled a *.next event* will be emitted to subscribers.

```swift
Observable.of(2, 30, 22, 5, 60, 1).filter{ $0 > 10 }.subscribe(onNext: {
    print($0)
})
```
The output will be:

```
30 22 60
```

<img width="821" alt="Screen Shot 2019-03-08 at 11.59.12 PM.png" src="https://qiita-image-store.s3.amazonaws.com/0/279562/aff2327c-2bfd-54aa-4e1e-a3008e6e565e.png">


:relaxed:
Congratulations :confetti_ball: :congratulations:  we have learnt the basic of RxSwift. Keep going :runner: :runner_tone3: :v: