AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79301741
Accepted
Deepak Sharma
Deepak Sharma
Asked: 2024-12-23 05:05:07 +0800 CST2024-12-23 05:05:07 +0800 CST 2024-12-23 05:05:07 +0800 CST

在 SwiftUI 中使用 AsyncStream 与 @Observable 宏

  • 772

AsyncStream我想了解iOS 17 引入宏的实用性@Observable,我们可以在其中直接观察模型中任何变量值的变化(并且观察跟踪甚至可以在 SwiftUI 视图之外进行)。因此,如果我AsyncStream在 SwiftUI 视图中使用连续的值流(例如文件的下载进度),则可以在同一个 SwiftUI 视图中使用onChange(of:initial)下载进度(存储为模型对象中的属性)观察到相同的值流。我正在寻找这两种方法的优点、缺点和局限性。

具体来说,我的问题与 Apple 的AVCam 示例代码有关,他们观察到以下几个状态。这是在CameraModel附加到 SwiftUI 视图的类中完成的。

    // MARK: - Internal state observations

// Set up camera's state observations.
private func observeState() {
    Task {
        // Await new thumbnails that the media library generates when saving a file.
        for await thumbnail in mediaLibrary.thumbnails.compactMap({ $0 }) {
            self.thumbnail = thumbnail
        }
    }
    
    Task {
        // Await new capture activity values from the capture service.
        for await activity in await captureService.$captureActivity.values {
            if activity.willCapture {
                // Flash the screen to indicate capture is starting.
                flashScreen()
            } else {
                // Forward the activity to the UI.
                captureActivity = activity
            }
        }
    }
    
    Task {
        // Await updates to the capabilities that the capture service advertises.
        for await capabilities in await captureService.$captureCapabilities.values {
            isHDRVideoSupported = capabilities.isHDRSupported
            cameraState.isVideoHDRSupported = capabilities.isHDRSupported
        }
    }
    
    Task {
        // Await updates to a person's interaction with the Camera Control HUD.
        for await isShowingFullscreenControls in await captureService.$isShowingFullscreenControls.values {
            withAnimation {
                // Prefer showing a minimized UI when capture controls enter a fullscreen appearance.
                prefersMinimizedUI = isShowingFullscreenControls
            }
        }
    }
}

如果我们看到结构,它是一个具有两个 Bool 成员的小结构。这些变化可以通过 SwiftUI 视图直接观察到。我想知道在这里使用并在 for 循环中不断迭代变化CaptureCapabilities是否有特定的优势或理由。AsyncStream

   /// A structure that represents the capture capabilities of `CaptureService` in
  /// its current configuration.
struct CaptureCapabilities {

let isLivePhotoCaptureSupported: Bool
let isHDRSupported: Bool

init(isLivePhotoCaptureSupported: Bool = false,
     isHDRSupported: Bool = false) {
    self.isLivePhotoCaptureSupported = isLivePhotoCaptureSupported
    self.isHDRSupported = isHDRSupported
}

  static let unknown = CaptureCapabilities()
}
  • 1 1 个回答
  • 115 Views

1 个回答

  • Voted
  1. Best Answer
    Rob
    2024-12-25T03:32:40+08:002024-12-25T03:32:40+08:00

    这里有几个问题:

    1. 抽象地回答这个问题AsyncSequence(这AsyncStream只是一个具体的例子)是一种更通用的模式。正确实施后,支持取消、随时间异步产生值以及在需要时产生值,并且当序列完成时具有“完成”的概念。ObservableObject/@Observable模式是一种更狭窄的模式(值得注意的是,@Observable非常适合 SwiftUI,在 UIKit/AppKit 中有点麻烦),用于发布对象某些状态的变化。对于您的特定示例(用于通知 SwiftUI 状态随时间的变化),观察和异步序列都可以完成这项工作;我不会因为其中一个而失眠。

    2. 当 UI 需要根据对象的状态进行更新时,观察相关模式非常自然。当您希望某个对象(例如此“相机”服务)根据其他事件更新其状态时,情况就不那么自然了(尽管您可以这样做)。我认为这里采用的异步序列模式没有内在缺陷。但您可以在此处采用任何一种模式。事实上,它们只是使用 从发布者创建异步序列values,因此两者有点混合。

    3. 如果您要使用异步序列,我们应该注意,其中所有的非结构化并发observeState都是一个值得怀疑的实现。它启动了四个非结构化任务,但无法取消它们。

      当然,他们是从 启动的AVCamApp,所以在这种情况下,他们并没有考虑停止CameraModel,但我真的不鼓励这种模式。不应该加入不可取消的行为,尤其是在开发人员可能倾向于复制和/或纳入其项目的演示项目中。

      通常会保存对这些任务的引用,然后提供stop/cancel函数来取消它们。或者,在这种情况下,更好的方法是放弃非结构化并发,将这四个任务包装在一个任务组中:

      private func observeState() async {
          await withDiscardingTaskGroup { group in
              group.addTask { @MainActor [self] in
                  for await thumbnail in mediaLibrary.thumbnails.compactMap({ $0 }) {
                      …
                  }
              }
      
              group.addTask { @MainActor [self] in
                  for await activity in await captureService.$captureActivity.values {
                      …
                  }
              }
      
              group.addTask { @MainActor [self] in
                  for await capabilities in await captureService.$captureCapabilities.values {
                      …
                  }
              }
      
              group.addTask { @MainActor [self] in
                  for await isShowingFullscreenControls in await captureService.$isShowingFullscreenControls.values {
                      …
                  }
              }
          }
      }
      

      然后,我们将改变start(我将其重命名run)以最后执行此操作:

      func run() async {
          // Verify that the person authorizes the app to use device cameras and microphones.
          guard await captureService.isAuthorized else { … }
          do {
              await syncState()
      
              try await captureService.start(with: cameraState)
              status = .running
              await observeState() // do this last; when `run` is cancelled, this will automatically be cancelled, too
          } catch { … }
      }
      

      然后View可以做类似的事情:

      var body: some View {
          CameraView(camera: camera)
              .task {
                  // Start the capture pipeline. If view is dismissed, asynchronous sequences will be cancelled.
                  await camera.run()
              }
      }
      

      现在,再次重申,原始代码示例是在 中执行此操作的App,因此此问题并未在此处出现。但上述内容将是一个更通用的解决方案,既可以在 中工作App,也可以在 中工作View。

      原始代码使用所有这些非结构化并发,并且没有考虑取消,这是一种反模式。我们希望CameraModel能够从App或 中使用View。(我将忽略 是否CameraModel是此对象的好名称;在我看来,它感觉像是一种“服务”,而不是一个简单的“模型”。)

    • 1

相关问题

  • 将复制活动的序列号添加到 Blob

  • Packer 动态源重复工件

  • 选择每组连续 1 的行

  • 图形 API 调用列表 subscribedSkus 状态权限不足,但已授予权限

  • 根据列值创建单独的 DF 的函数

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve