Skip to content

Instantly share code, notes, and snippets.

@ankittlp
ankittlp / multipleHeavyAsynchronousCallBackTask.swift
Created December 21, 2022 21:30
MultipleHeavyAsynchronousCallBackTask
func multipleHeavyAsynchronousCallBackTask(start: Int, end: Int, completionHandler: @escaping ([Int]) -> Void) {
//1. Gets the array of numbers (A dummy heavy operation)
HeavyOperationApi.shared.heavyNumberArray(from: start, to: end) { numbers in
//2. Using the numbers array to fillter for Even number (A Dummy heavy operation)
HeavyOperationApi.shared.heavyFilterEvenNumberFrom(arrayOf: numbers) { evenNumbers in
// 3. Doing Random mapping of even numbers array (A Dummy Heavy operation)
HeavyOperationApi.shared.heavyRandomMapping(arrayOf: evenNumbers) { number in
return number + 10000000
} completion: { transformedNumbrs in
completionHandler(transformedNumbrs)
@ankittlp
ankittlp / SomeHeavyOperationTasks.swift
Last active December 23, 2022 05:38
SomeHeavyOperationTasks
import Foundation
func printWithThreadInfo(tag: String) {
print("Thread \(Thread.current) - \(tag) - \(Thread.isMainThread)")
}
class SomeHeavyOperationTasks {
func someHeavySynchronousTask() -> [Int] {
var number: [Int] = []
@ankittlp
ankittlp / NetworkLayerCallBackTypeRequestExecutor.swift
Last active May 22, 2022 19:03
NetworkLayerCombineTypeRequestExecutor.swift
class WebApiClient: RequestExecutor {
private var configuration: URLSessionConfiguration
private var session: URLSession
init(sessionConfiguration: URLSessionConfiguration = URLSessionConfiguration.default) {
configuration = URLSession.shared.configuration
session = URLSession(configuration: configuration)
@ankittlp
ankittlp / CombineStreamFail_HowToOverCome.swift
Created May 22, 2022 16:45
CombineStreamFail_HowToOverCome
// Example of One-Shot piblisher with Stream Failure.
// As we find the value 0 in the stream, we throw an error. This error is eventually catched and replaced with Just(-1) publisher.
// But after a failed value will activates the catch operator and the pipeline will cease to react further.
struct SimpleError: Error {}
let numbers = [5, 4, 3, 2, 1, 0, 9, 8, 7, 6]
let cancellable = numbers.publisher
.tryMap({ val in
guard val != 0 else {throw SimpleError()}
@ankittlp
ankittlp / URLSessionDataTaskPublisher_ErrorHandling.swift
Last active May 7, 2022 20:51
URLSessionDataTaskPublisher_ErrorHandling
enum APIError: Error, LocalizedError {
case invalidServerResponse
case unknown
var errorDescription: String? {
switch self {
case .unknown:
return "Unknown error"
case .invalidServerResponse:
return "Invalid Server Response"
@ankittlp
ankittlp / URLSessionDataTaskPublisher_Operators.swift
Last active May 7, 2022 20:25
URLSessionDataTaskPublisher_Operators
var cancellable: AnyCancellable?
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
cancellable = URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data } // 1
.decode(type: [Post].self, decoder: JSONDecoder()) // 2
.replaceError(with: []) // 3
.eraseToAnyPublisher() // 4
.sink(receiveValue: { posts in
@ankittlp
ankittlp / URLSessionDataTaskPublisher_basic.swift
Created May 7, 2022 14:29
URLSessionDataTaskPublisher_basic
let urlSessionPublisher = URLSession.shared.dataTaskPublisher(for: url)//.map { $0.data }
let subscription = urlSessionPublisher.sink(receiveCompletion: { (error) in
print("error \(error)")
}) { (data,response) in
print("Data \(String(data: data, encoding: .utf8)) - Response - \(response)" )
}
@ankittlp
ankittlp / NetworkLayerProtocolCombine.swift
Created May 7, 2022 12:52
NetworklayerProtocolsCombine
// An AssociatedType Protocol: Request type to be implemented by Concrete Requests
protocol Request {
associatedtype Response: Decodable // 1. A Response Type constrained to be decodable
associatedtype ResponseParser: ResponseParserType where ResponseParser.Response == Response // 2 Response parser contrained to be confirming to ResponseParserType
// 3 Basic properties required by a request
var baseUrl: String { get }
var path: String { get }
var method: String { get }
var header: [String: String]? { get }
@ankittlp
ankittlp / NetworkLayerCallBackTypeRequestExecutor.swift
Created May 1, 2022 18:12
NetworkLayerCallBackTypeRequestExecutor.swift
class WebApiClient: RequestExecutor {
private var configuration: URLSessionConfiguration
private var session: URLSession
init(sessionConfiguration: URLSessionConfiguration = URLSessionConfiguration.default) {
configuration = URLSession.shared.configuration
session = URLSession(configuration: configuration)
@ankittlp
ankittlp / NetworkingLayerProtocolsForCallBackType.swift
Last active May 6, 2022 19:30
Networking LayerProtocols for CallBack type
// An AssociatedType Protocol: Request type to be implemented by Concrete Requests
protocol Request {
associatedtype Response: Decodable // 1. A Response Type constrained to be decodable
associatedtype ResponseParser: ResponseParserType where ResponseParser.Response == Response // 2 Response parser contrained to be confirming to ResponseParserType
// 3 Basic properties required by a request
var baseUrl: String { get }
var path: String { get }
var method: String { get }
var header: [String: String]? { get }