🍎 iOS/GCD

[iOS/GCD] 4. async/await (Swift 5.5 ~) (feat. vs Combine, RxSwift)

dev_zoe 2023. 7. 24. 00:59
반응형

async/await이 나오게 된 배경

메인 스레드에서 다른 스레드로 작업을 보내고 -> 해당 스레드에서 다른 스레드로 작업을 보내고 .... 이런식으로 이어나가면서 completionHandler를 진행하게 되면, 콜백 지옥에 빠지게된다.

func processImageData(completionHandler: (_ result: Image) -> Void) {
	loadWebResource("a.txt") { dataResource in
    	loadWebresource("b.txt") { dataResource in
        	decodeImage(dataResource, imageResource) { imageTmp
            .....

 

async/await를 도입하면?

func processImageData() async throws -> Image {
	let dataResouyrce = try await loadWebresource("a.txt")
    let imageResource = try await loadWebResource("b.txt")
    .....
 
 }

- 코드가 매우 깔끔해진다.

 

1) completionHandler(이스케이핑 클로저) 대신에 async throws -> 리턴형 으로 바꾸고

2) 함수 호출 시, try await을 붙여서 작업이 끝날 때, 작업이 끝난 결과를 return해주게 되어 컴플리션 핸들러 대체

 

async/await VS Combine

https://developer.apple.com/documentation/combine/using-combine-for-your-app-s-asynchronous-code

 

Using Combine for Your App’s Asynchronous Code | Apple Developer Documentation

Apply common patterns to migrate your closure-based, event-handling code.

developer.apple.com

- async/await이 Combine을 대체한다?!!! (하지만 Swift 5.5 라는 정말 최근에 나온 개념이라 기존의 코드를 모두 리팩토링 하는 것은 한계가 있을듯 ..)

https://medium.com/@GetInRhythm/closures-vs-combine-vs-async-await-993eb1da4d44

 

Closures Vs. Combine Vs. Async Await

Closures are a fundamental feature of Swift that allow developers to define self-contained blocks of functionality.

medium.com

- 해당 글만 봐도 Async Await이 더 직관적이고 코드 길이가 더 짧아서 좋은것같다.

 

Combine vs RxSwift

https://eunjin3786.tistory.com/67

 

RxSwift vs Combine - 스펙 / 성능 / 개념 비교

WWDC 2019에서 Combine이 발표되었다. Combine은 Rx와 똑같다! 라고 말하던데 정말 똑같을까..? 🤔 Rx와 Combine을 비교해보자 1. 스펙 비교 Rx와 Combine은 모두 Reactive 프로그래밍을 위한 framework이다 하지만 R

eunjin3786.tistory.com

- Combine: iOS 13부터 지원, SwiftUI에 최적화

- RxSwift: iOS 8부터 지원

- 장기적으로는 iOS가 SwiftUI를 엄청 밀고있어서, Combine이 RxSwift를 나~~~중 가서는 뒤집을 날이 올 수도 있을것같다.

반응형