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

in #rxswift6 years ago

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한 데이타
Sort:  

Congratulations @jsharp! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.15
TRX 0.23
JST 0.032
BTC 91248.01
ETH 2481.77
USDT 1.00
SBD 0.68