A demonstration for bridging between Combine and your new async functions

Overview

CombineAsyncually

This is a DEMONSTRATION of how you can bridge the new async / await functionality in Swift 5.5 with Combine.

There is NO WARRANTY. There is also a high chance this code may set your Mac, iPhone or other device on fire.

It provides three simple utilities that let you go mix and match your async functions and Combine publishers:

Async Function to Combine

These samples use the withPublisher1 and withThrowingPublisher functions to run an async closure and emit the result.

func myAsyncFunction() async -> String {
    return "Hello 👋"
}

// For non-throwing functions
withPublisher {
    await myAsyncFunction()
}
    .sink {
        print($0)   // Hello 👋
    }

// For throwing ones
withThrowingPublisher {
    try await someThrowingFunction()
}
    .catch {
        // handle error
    }
    .sink {
        // handle value
    }

Mixing Async Functions in Combine Publisher chains

You can use the .await and .tryAwait operators to mix and match your Combine publishers and async code.

// Non throwing functions
somePublisher
    .await { value in 
        return await someAsyncFunction(value)
    }
    .sink {
        // handle result of someAsyncFunction
    }
    
// Throwing ones
somePublisher
    .tryAwait { value in
        return try await someThrowingAsyncFunction(value)
    }
    .catch {
        // handle error
    }
    .sink {
        // handle result of someAsyncFunction
    }

Awaiting Your Publishers

You can also call .get() on supported Publishers2 to await for the Publisher to complete.

let result1 = try await Just("Hello!").get()            // Hello!    
let result2 = try await somePublisher.first().get()

Learning more

This repository is here to support a presentation given at Melbourne CocoaHeads on the 10th of June 2021. You can watch it here.

Notes

  1. They're named to align with the withTaskGroup and withThrowingTaskGroup (and friends) functions.
  2. We only support publishers that are guaranteed to emit once because this is just too dangerous. Use .first() to get around this.
You might also like...
🎭 Swift async/await & Actor-powered effectful state-management framework.
🎭 Swift async/await & Actor-powered effectful state-management framework.

🎭 Actomaton 🧑‍🎤 Actor + 🤖 Automaton = 🎭 Actomaton Actomaton is Swift async/await & Actor-powered effectful state-management framework inspired by

A simple network layer for use in small iOS projects with async/await support

SimpleNetwork Intro SimpleNetwork is simple network layer for use in small projects. Swift Package Manager Note: Instructions below are for using Swif

Example project showing how to use async/await with iOS 13
Example project showing how to use async/await with iOS 13

ios13AsyncAwait Example project showing how to use async/await with iOS 13 Article This source code is a part of an article published at This Dev Brai

Using async / await on iOS 13: everything you need to know
Using async / await on iOS 13: everything you need to know

Using async / await on iOS 13: everything you need to know! 🚀 Content This repository contains the code sample I've used during December 14th's lives

iOS 13-compatible backports of commonly used async/await-based system APIs that are only available from iOS 15 by default.

AsyncCompatibilityKit Welcome to AsyncCompatibilityKit, a lightweight Swift package that adds iOS 13-compatible backports of commonly used async/await

Hydra: Lightweight full-featured Promises, Async-Await Library in Swift

Async Functions for ECMAScript The introduction of Promises and Generators in EC

Swift TableView pagination with async API request.
Swift TableView pagination with async API request.

SwiftTableViewPagination Swift TableView pagination with async API request. Output UML Create puml file. $ cd SwiftTableViewPagination/scripts/swiftum

PixabayImageSearchSample - SwiftUI + LazyVGrid + Pixabay API + Codable + sync/async Sample
PixabayImageSearchSample - SwiftUI + LazyVGrid + Pixabay API + Codable + sync/async Sample

PixabayImageSearchSample SwiftUI + LazyVGrid + Pixabay API + Codable + sync/asyn

AsyncTaskKit - contains some additions to async/await Task

AsyncTaskKit This repo contains some additions to async/await Task. In general i

Comments
  • Why so overengineered? Am I missing something?

    Why so overengineered? Am I missing something?

    I get this is a demo but why not simply use the Future builder?

    func TaskPublisher<T>(closure: () async throws -> T)  -> AnyPublisher<T, Error> {
        Deferred {
            Future { emitter in
                Task {
                    do {
                        let result = try await closure()
                        emitter(success(result))
                    } catch {
                        emitter(error(error))
                    }
                }
            }
        }
    }
    

    am I missing something?

    opened by ursusursus 0
Owner
null
🍴 Parallelize two or more async functions

Fork Parallelize two or more async functions What is Fork? Fork allows for a single input to create two separate async functions that return potential

Zach 4 Oct 15, 2022
A lightweight swift network layer with Combine, Async-Await, and a traditional completion block.

CombineNetwork A simple light-weight network library to make network requesting simpler. It supports newer techonology such as async/await as well as

Dushant Singh 4 Jan 3, 2022
AsyncExtensions aims to mimic Swift Combine operators for async sequences.

AsyncExtensions AsyncExtensions provides a collection of operators, async sequences and async streams that mimics Combine behaviour. The purpose is to

AsyncCommunity 200 Dec 27, 2022
Demonstration of using Tasks and TaskGroup to thread a calculation.

TasksTest Demonstration of using Tasks and TaskGroup to thread a calculation. The calculation takes place in a separate Swift class that can be reused

null 0 Dec 27, 2021
GroupWork is an easy to use Swift framework that helps you orchestrate your concurrent, asynchronous functions in a clean and organized way

GroupWork is an easy to use Swift framework that helps you orchestrate your concurrent, asynchronous functions in a clean and organized way. This help

Quan Vo 42 Oct 5, 2022
Async and concurrent versions of Swift’s forEach, map, flatMap, and compactMap APIs.

CollectionConcurrencyKit Welcome to CollectionConcurrencyKit, a lightweight Swift package that adds asynchronous and concurrent versions of the standa

John Sundell 684 Jan 9, 2023
straightforward networking and error handling with async-await and URLSession

AsyncAwaitNetworkingPlayground How To Run Just clone the project, open it and run. Some notes about AsyncAwaitNetworkingPlayground It's a straightforw

Fırat Yenidünya 17 Dec 11, 2022
⚡️ Fast async task based Swift framework with focus on type safety, concurrency and multi threading

Our apps constantly do work. The faster you react to user input and produce an output, the more likely is that the user will continue to use your appl

Said Sikira 814 Oct 30, 2022
Edit images and video with async / await in Swift, powered by Metal.

AsyncGraphics The core value type in AsyncGraphics is a Graphic. It's like an image, tho it can be used with various async methods. Documentation Swif

Anton Heestand 33 Dec 27, 2022
Hydra ⚡️ Lightweight full-featured Promises, Async & Await Library in Swift

Lightweight full-featured Promises, Async & Await Library in Swift What's this? Hydra is full-featured lightweight library which allows you to write b

Daniele Margutti 2k Dec 24, 2022