Merge different AsyncStream types

Published by malhal on

When I first used AsyncStream with merge from AsyncAlgorithms I struggled with merging different stream result types and had experimented with building a protocol that each stream’s result type enum implemented. That way all the streams used the same protocol type and could be merged. I realised today that I could simply map each stream, do the work I needed to inside of map instead of inside the merged for await and then return a Void type. Thus all the streams could be merged because their type was just Void, e.g.

let events = LocationManagerEvents()

let locationEvents = events.locationEvents.map { a in
    print("locs")
    return
}
let authorizationEvents = events.authorizationEvents.map { a in
    print("auths")
    try? await Task.sleep(for: .seconds(0)) // Just testing that awaits can be done
    return
}
let failureEvents = events.failureEvents.map { a in
    print("fails")
    return
}

for await event in merge(merge(locationEvents, authorizationEvents), failureEvents) {
    print("\(c) \(event)") // now just void
//    switch event {
//        case LocationsEvent.didUpdateLocations(let locations):
//            print("locations updated \(locations)")
//        case AuthorizationEvent.didChangeAuthorization(let status, _):
//            self.authorised = status != .notDetermined
//        case FailureEvent.failed(let error):
//            print("Failed with \(error)")
//        default:
//            break
//    }
}