You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fetchThumbnail 메서드 호출 이후 유저가 데이터에 변화를 주는 행동을 하게 될 경우, URLSession은 임시 정지 되며 데이터 변경 작업을 먼저 실행
이후 시스템에서 fetchThumbnail 메서드로 돌아가거나 다른 메서드를 실행 - 의도했던 스레드가 아닌 곳에서 실행 가능
따라서 Swift에서는 await 키워드를 활용하도록 권장하는 것.
[Thread Safety and Async/Await]
비동기 실행 이미지
C. 동기 메서드에 비동기 메서드를 담는 방법
privatefunc fetchData(){
// Task없이는 비동기처리 작업을 할 수 없다.
// Task {
do{letpokemonData=tryawaitNetworkManager.shared.fetchPokemon()PersistenceManager.shared.savePokeData(pokemonData.id)self.pokemonName = pokemonData.name
self.setImage(with: pokemonData)}catchlet error{iflet error = error as?NetworkError{print("네트워크 오류가 발생했습니다.")}else{print("예측 불가능한 에러가 발생했어요.")}}
//}
}
Task라는 비동기 처리에 감싸면 일반 메서드 내부에 비동기 작업을 실행할 수 있게 된다. 앞서 정리한대로 일반 메서드는 동기적으로(synchronous) 처리를 하기 때문에 비동기 처리(asynchronous)를 하는 fetchPokemon 메서드를 내부에서 실행할 수 없다.
D. async Alternative && Continuation [🚧 추가 공부 중]
// 이전 메서드
func getPersistentPosts(completion:@escaping([Post],Error?)->Void){do{letreq=Post.fetchRequest()
req.sortDescriptors =[NSSortDescriptor(key:"date"), ascending: true)]letasyncRequest=NSAsynchronousFetchRequest<Post>(fetchRequest: req){ result incompletion(result.finalResult ??[],nil)}tryself.managedObjectContext.execute(asyncRequest)}catch{completion([], error)}}
// async 적용 > continuation
func persistentPost() asycn throws->[Post]{
typeAlias PostContinuation =CheckedContinuation<[Post],Error>returntryawaitwithCheckedThrowingContinuation{(continuation:PostContinuation in
self.getPersistentPosts{ posts, error in
continuation.resume(throwing: error)} else {
continutation.resume(returning: posts)})}}
우리는 await를 통해 권한을 시스템으로 넘기고 결과값이 돌아오기를 기다리며 클로저를 통해 어떤 작업이 이뤄져야하는지 알린다. 메서드가 실행된 이후, completion block을 통해 우리는 해당 결과값을 자유롭게 던질 수 있게 되는데 이를 continuation이라 부른다.
continuation은 한번만 호출되어야 한다.
- 간혹 API 콜 내부의 메서드가 빨리 끝나는 경우가 존재한다. url을 변환하는 과정이나 이미지 데이터를 변환하기만 하는 경우 빨리 처리가 가능한데, 이런 경우는 thread가 백그라운드에서 실행이 되어도 문제가 없다. 반대로 시간이 걸리는 메서드의 경우 - 비동기처리롤 메서드를 실행한다.