apple/UIKit & ReactiveX

RxSwift Community - Action 🐣

lgvv 2022. 1. 19. 00:21

✅ 이번 시간에는 RxSwift Community에 있는 Action을 알아볼 예정이야.

 

어떻게 알아보게 되었느냐? 이번에 RxSwift를 공부하면서 모든 챕터를 꼼꼼하게 읽어 있는데, 이 부분이 있어서 보게 되었어.

상당히 유용할 것 같더라고.

 

게다가 RxSwift Community에 Pinned 되어 있는걸 보니까.. 뭔가 대단할 것 같다는 생각도 들어.

2022.01.19 기준

 

✅ 코드의 위치

https://github.com/RxSwiftCommunity/Action

 

GitHub - RxSwiftCommunity/Action: Abstracts actions to be performed in RxSwift.

Abstracts actions to be performed in RxSwift. Contribute to RxSwiftCommunity/Action development by creating an account on GitHub.

github.com

 

아주 간단한 예시를 하나 보도록 하자!

 

✅ ActionViewController.swift


import UIKit
import RxCocoa
import RxSwift
import SnapKit
import Then
import Action

class ActionViewController: UIViewController {
    
    var bag = DisposeBag()
    
    var button1 = UIButton().then {
        $0.setTitle("button1", for: .normal)
        $0.backgroundColor = .brown
    }
    
    let button2 = UIButton().then {
        $0.setTitle("button2", for: .normal)
        $0.backgroundColor = .cyan
    }
    
    var button3 = UIButton().then {
        $0.setTitle("button3", for: .normal)
        $0.backgroundColor = .link
    }
    
    let action1: Action<Void ,Void> = Action {
        print("Doing some work")
        return Observable.empty()
    }
    
    let action2 = Action<String ,String> { input in
        print("action2 \(input)")
        return .just(input)
    }
    
    lazy var action3 = Action<String ,Void> { input in
        let alert = UIAlertController(title: input, message: input, preferredStyle: .alert)
        let okAction = UIAlertAction.Action("OK", style: .default)
        let cancelAction = UIAlertAction.Action("Cancel", style: .destructive)
        [okAction, cancelAction].forEach { alert.addAction($0) }
        self.present(alert, animated: true, completion: nil)
        return Observable.empty()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        [button1, button2, button3].forEach {
            view.addSubview($0)
        }
        
        button1.snp.makeConstraints {
            $0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
        }
        button2.snp.makeConstraints {
            $0.top.equalTo(button1.snp.bottom)
            $0.leading.trailing.equalToSuperview()
        }
        button3.snp.makeConstraints {
            $0.top.equalTo(button2.snp.bottom)
            $0.leading.trailing.equalToSuperview()
        }
        
        bindAction()
    }
    
    func bindAction() {
        button1.rx.action = action1
        button2.rx.bind(to: action2, input: "say Hello?")
        button3.rx.bind(to: action3, input: "Button3")
    }
}

아주 간단한 예시이고, RefreshControl에서도 사용할 수 있대

 

RxCommunity - Action 부분에서 Tests를 가보면 다른 예시도 볼 수 있으니까 궁금하면 확인해보기!!