Skip to content

Asynchronous image decoding #860

@FaizanDurrani

Description

@FaizanDurrani

I am trying to implement an image decoder that needs to call out an async context, is there a better way to achieve this instead of using Semaphores?

// Example
public struct CustomImageDecoder: ImageDecoding {
  func decode(_ data: Data) throws -> ImageContainer {
    let sem = DispatchSemaphore(value: 0)
    nonisolated(unsafe) var data = data
    nonisolated(unsafe) var error: Error?

    CustomImageDecoderImplementation.decode(
      data: data,
      completion: { result in
        switch result {
          case .success(let success):
            data = success
          case .failure(let failure):
            error = failure
        }
        sem.signal()
      }
    )

    switch sem.wait(timeout: .now() + 30) {
      case .timedOut:
        return data
      case .success:
        break
    }

    guard error == nil else { 
      throw error
    }

    return data
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions