RxSwiftCommunity / Action

Abstracts actions to be performed in RxSwift.
MIT License
875 stars 150 forks source link

Binding observable to an action #204

Closed fenuks closed 5 years ago

fenuks commented 5 years ago

I quickly skimmed through the code, and it seems that Observable cannot be bind to an Action, I couldn't find related issues as well.

It would be useful, e.g. when using Observable.combineLatest to bind Observable to Action. Simple example to illustrate that.

        let disposeBag = DisposeBag()
        let exampleAction: Action<(Int, Int, Int), (Int, Int, Int)> = Action { (a, b, c) in Observable.just((a+1, b+1, c+1)) }
        Observable.just((1, 2, 3)).bind(to: exampleAction).disposed(by: disposeBag)

It is not difficult to write extension for ObservatleType to allow such use-case.

extension ObservableType {
    func bind<T>(to action: Action<Element, T>) -> Disposable {
        return subscribe { e in
            switch e {
            case let .next(element):
                action.execute(element)
            case let .error(error):
                print("Binding error to action: \(error)")
            case .completed:
                break
            }
        }
    }
}

Are there any reasons for this not being possible out-of-box?

hakkurishian commented 5 years ago

This is supported out of the box using the inputs observer, like so:

let exampleAction: Action<(Int, Int, Int), (Int, Int, Int)> = Action { (a, b, c) in Observable.just((a+1, b+1, c+1)) }

Observable.just((1, 2, 3)).bind(to: exampleAction2.inputs).disposed(by: disposeBag)
fenuks commented 5 years ago

Thank you, that's very clean way of doing it. 👍 I will migrate to this solution in my code.