Pattern for AsyncStream - to many relationship

Hello, I have an architectural question. Imagine this sample
https://developer.apple.com/documentation/swift/asyncstream

slightly modified so it doesn't use a static var

extension QuakeMonitor {

    var quakes: AsyncStream<Quake> {
        AsyncStream { continuation in
            let monitor = QuakeMonitor()
            monitor.quakeHandler = { quake in
                continuation.yield(quake)
            }
            continuation.onTermination = { @Sendable _ in
                 monitor.stopMonitoring()
            }
            monitor.startMonitoring()
        }
    }
}

Suppose multiple receivers are interested in getting updates via the quakes stream, how would one architect such solution? E.g. let's say we have two views which exist at the same time such as below. Is there a way both can get updates simultaneously?

Alternatively, is it possible to "hand off" a stream from one object to another?

class MyFirstView: UIView {
   
   
  private var quakeMonitor: QuakeMonitor
   
  init(quakeMonitor: QuakeMonitor) {
    self.quakeMonitor = quakeMonitor
  }
   
  func readQuakeData() {
    for await quake in quakeMonitor.quakes {
      print ("Quakes in first view: \(quake.date)")
    }
  }
}


class MySecondView: UIView {
   
  private var quakeMonitor: QuakeMonitor
   
  init(quakeMonitor: QuakeMonitor) {
    self.quakeMonitor = quakeMonitor
  }
   
  func readQuakeData() {
    for await quake in quakeMonitor.quakes {
      print ("Quakes in second view: \(quake.date)")
    }
  }
}

Suppose multiple receivers are interested in getting updates via the quakes stream, how would one architect such solution?

The question of how best to achieve this goal is a subject of ongoing debate. I recommend that you bounce over to Swift Forums > Using Swift, where you’ll find a wider range of opinions.

Please post your Swift Forums URL so that interested folks can follow you over.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Pattern for AsyncStream - to many relationship
 
 
Q