Basic of RxSwift
ReactiveX (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 .
Observable and Observer
Whenever people talk about RxSwift first thing in my mind is Observable and Observer.
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:
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>)->())
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.
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.
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.
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
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 itsown
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
스캔
Scan starts with initial seed value and is used to aggregate value just like reduce in 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
필터
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.
Observable.of(2, 30, 22, 5, 60, 1).filter{ $0 > 10 }.subscribe(onNext: {
print($0)
})
The output will be:
30 22 60
Congratulations we have learnt the basic of RxSwift. Keep going
Reference
이 문제에 관하여(Basic of RxSwift), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/phansreypich/items/c47eb7eeff7d1fbe8b0d텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)