---
# System prepended metadata

title: ReactiveX Swift 使用筆記
tags: [Learning Note]

---

###### tags: `Learning Note`
ReactiveX Swift 使用筆記
===

### Create Observable

* 1. 直接建立序列
```swift=
Observable<T>.create{ observer -> Disposable in

            observer.onNext(T)
            observer.onCompleted()
            // oncompleted need handle .onComplete
            return Disposables.create()
            
}
```

* 2. just
```swift=
Observable.just(T)
```

* 3. of 
```swift=
Observable.of("a", "b", "c")
```

### Bind
* ForUIImage
```swift=
let image: Observable<UIImage> = Observable.create { (observer) -> Disposable in
                    observer.onNext( { () -> UIImage in
                        // url is Images' URL
                        let read_data: Data = try! Data(contentsOf: url!)
                        return UIImage(data: read_data)!

                        }() )
                    
                    observer.onCompleted()
                    return Disposables.create()
                }
                
image.bind(to: cell.img_view.rx.image).disposed(by: cell.disposeBag)
```

* For UIRefreshControl (UICollectionView)

```swift=
refreshControl.rx.controlEvent(.valueChanged).bind{ (_) in
            
            debugPrint("refresh")
                
            // somthing to do

            // Refresh End
            self.refreshControl.endRefreshing()
            
            // Reload Data
            self.collectview.reloadData()
            
        }
```

* For some boolean value
```swift=
let observable = Observable<Bool>.of(true, false, true)

let button = UIButton()

observable.bind(to: button.rx.isEnable).disposed(by: disposeBag)

let image = UIImage()

observable.map{ !$0 }.bind(to: button.rx.isHidden).disposed(by: disposeBag)
```

### Subscribe
* For Observable 
    #### Observalbe.subscribe()
```swift=
Observable.of("a", "b", "c")
            .subscribe(onNext: { element in
                debugPrint(element)
            }
        )
        .disposed(by: disposeBag)
```

* For UIbutton
```swift=
button.rx.tap
        .subscribe(onNext: { [self] in // or [weak self] in
                // something to do 
            }
        )
        .disposed(by: disposeBag)
```

### RxDataSource
* UICollectionView 
```swift=
struct CustomSection {
    var header: String
    var items: [Item]
}
 
extension CustomSection : SectionModelType {
    typealias Item = T // Custom class
     
    var identity: String {
        return header
    }
     
    init(original: CustomSection, items: [Item]) {
        self = original
        self.items = items
    }
}
```

```swift=
// In viewDidLoad()
let items = Observable.just( [CustomSection(header: "", items: [T])] )

let dataSource = RxCollectionViewSectionedReloadDataSource
    <CustomSection>(
    configureCell: { (dataSource, collectionView, indexPath, element) in

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! customCollectCell

        return cell

    }
)

items.bind(to: collectview.rx.items(dataSource: dataSource))
    .disposed(by: disposeBag)
```
* Cell selected
```siwft=

collectview.rx.itemSelected
    .subscribe(onNext: { [self] indexPath in

        if(self.mode == .Edit){
            if ((self.arrSelectedIndex.contains(indexPath))) {
                self.arrSelectedIndex = (self.arrSelectedIndex.filter { $0 != indexPath})
            }
            else {
                self.arrSelectedIndex.append(indexPath)
            }
            self.collectview.reloadData()
        }

    })
    .disposed(by: disposeBag)
         
        
// Item selected
```

### Observable variable
* PublishSubject 不需有初始值
```swfit=
var boolSubject = PublishSubject<Bool>()
````
* BehaviorSubject 需有初始值
```swfit=
var boolSubject = BehaviorSubject<Bool>(value: true)
````

* 產生Event
```swift=
var boolSubject = PublishSubject<Bool>()

boolSubject.onNext(true)
boolSubject.onNext(false)
boolSubject.onCompleted()
```

* 觀察
```swift=
var boolSubject = PublishSubject<Bool>()

boolSubject.subscribe(onNext: { _ in 
    
    }).disposed(by: disposeBag)
```