jsharp avatar

Synchronous와 Asynchronous Code의 차이 (From RxSwift Reactive Programming with Swift)

jsharp

Published: 01 Oct 2018 › Updated: 01 Oct 2018Synchronous와 Asynchronous Code의 차이 (From RxSwift Reactive Programming with Swift)

Synchronous와 Asynchronous Code의 차이 (From RxSwift Reactive Programming with Swift)

Synchronous code

Swift에서 Array의 각 element에 접근하는것은 다음 두가지를 보장

  1. Synchronously 실행됨
  2. Collection은 iterate하는동안 immutable함
var array = [1, 2, 3]
for number in array {
    print(number)
    array = [4, 5, 6]
}

print(array)

우리는 위의 코드가 synchronous하게 실행되기 때문에 어떻게 찍힐지 예상할 수 있음.

Asynchronous code

var array = [1, 2, 3]
var currentIndex = 0

//this method is connected in IB to a button
@IBAction func printNext(_ sender: Any) {
  print(array[currentIndex])
  if currentIndex != array.count-1 {
    currentIndex += 1
  }
}

위의 코드는 유저가 탭할때마다 출력해서, 1,2,3이 찍힐거라고 예상할 수 없음. 다른 쓰레드에서 array 를 변경했을 수도 있기 때문.

그렇기 때문에 Asynchronous Code를 짤때 다음 두가지에 대해 고민을 해야함

  1. 코드들의 실행 순서
  2. 공유되어진 mutable한 데이타

Leave Synchronous와 Asynchronous Code의 차이 (From RxSwift Reactive Programming with Swift) to:

Written by

Read more #rxswift posts


Best Posts From jsharp

We have not curated any of jsharp's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From jsharp