[swift-evolution] [Concurrency] A slightly different perspective

Michel Fortin michel.fortin at michelf.ca
Mon Sep 4 12:53:52 CDT 2017


> Le 4 sept. 2017 à 10:01, Wallacy via swift-evolution <swift-evolution at swift.org> a écrit :
> 
> func processImageData1a() async ->
>  Image {
>   let dataResource  = async loadWebResource("dataprofile.txt")
>   let imageResource = async loadWebResource("imagedata.dat")
>   
>   // ... other stuff can go here to cover load latency...
>   
>   let imageTmp    = await decodeImage(dataResource, imageResource) // compiler error if await is not present.
>   let imageResult = await dewarpAndCleanupImage(imageTmp)
>   return imageResult
> }
> 
> 
> If this (or something like that) is not implemented, people will create several versions to solve the same problem, so that later (Swift 6?) will be solved (because people want this), and we will live with several bad codes to maintain.

Just to be sure of what you are proposing, am I right to assume this would be compiled down to something like this?

func processImageData1a(completion: (Image) -> ()) {
  var dataResource: Resource? = nil
  var imageResource: Resource? = nil
  var finishedBody = false

  func continuation() {
    // only continue once everything is ready
    guard finishedBody else { return }
    guard dataResource = dataResource else { return }
    guard imageResource = imageResource else { return }

    // everything is ready now
    decodeImage(dataResource, imageResource) { imageTmp in
      dewarpAndCleanupImage(imageTmp) { imageResult in
        completion(imageResult)
      }
    }
  }

  loadWebResource("dataprofile.txt") { result in
    dataResource = result
    continuation()
  }
  loadWebResource("imagedata.dat") { result in
    imageResource = result
    continuation()
  }

  // ... other stuff can go here to cover load latency...

  finishedBody = true
  continuation()
}


This seems more lightweight than a future to me. I know I've used this pattern a few times. What I'm not sure about is how thrown errors would work. Surely you want error handling to work when loading resources from the web.


-- 
Michel Fortin
https://michelf.ca



More information about the swift-evolution mailing list