AsyncStream在视图上垃圾邮件,而AsyncPublisher不会
创始人
2024-09-21 09:30:31
0

使用 AsyncPublisher 来代替 AsyncStream。

以下是使用 AsyncPublisher 进行演示的示例代码(假设我们想要在视图中渲染一系列异步生成器生成的数据):

// 定义异步生成器以生成数据
func dataGenerator() -> AsyncGenerator {
    AsyncStream { continuation in
        // 在此处生成数据并将其发送到视图
        continuation.yield("item 1")
        continuation.yield("item 2")
        continuation.yield("item 3")
        continuation.finish()
    }.makeAsyncPublisher().makeAsyncGenerator()
}

// 使用异步生成器在视图中渲染数据
struct ContentView: View {
    var body: some View {
        List {
            ForEach(dataGenerator(), id: \.self) { item in
                Text(item)
            }
        }
    }
}

上述代码使用 AsyncStream 来创建一个异步生成器来生成数据,并在视图中渲染该数据。 但是,由于 AsyncStream 会在生成器返回完成信号时继续发送事件,因此会导致视图被垃圾邮件。

为了避免这种情况,我们可以使用 AsyncPublisher 来创建异步生成器。 在此示例中,我们将 AsyncStream 包装在 AsyncPublisher 中,然后将其转换回 AsyncGenerator。这将导致异步生成器仅在返回完成信号时发送一次事件,从而在视图中避免垃圾邮件。

示例代码如下:

// 定义异步生成器以生成数据
func dataGenerator() -> AsyncGenerator {
    AsyncPublisher { subscriber in
        // 在此处生成数据并将其发送到视图
        subscriber.receive("item 1")
        subscriber.receive("item 2")
        subscriber.receive("item 3")
        subscriber.receive(completion: .finished)
        return AnyCancellable {}
    }.makeAsyncGenerator()
}

// 使用异步

相关内容

热门资讯

epoker免费透视脚本!hh... epoker免费透视脚本!hhpoker真的假的(透视)app-本来曝光存在有挂1、下载好epoke...
透视开挂!wepokerplu... 透视开挂!wepokerplus万能挂(透视)wpk透视工作室,教程总结(有挂透视)-哔哩哔哩1.w...
wpk辅助插件!wepoker... wpk辅助插件!wepoker辅助透视软件(透视)神器-真是辅助真的是有挂运wepoker辅助透视软...
透视曝光!hhpoker是真的... 透视曝光!hhpoker是真的吗(透视)hhpoker辅助挂,教程练习(有挂工具)-哔哩哔哩1)hh...
hhpoker德州透视挂!哈糖... hhpoker德州透视挂!哈糖大菠萝有没有挂(透视)神器-一贯普及存在有挂1、哈糖大菠萝有没有挂免费...
透视揭露!aapoker如何设... 透视揭露!aapoker如何设置胜率(透视)wepoker辅助器最新版本更新内容,教程烘培(存在有挂...
wepoker辅助软件价格!德... wepoker辅助软件价格!德普之星透视辅助插件(透视)攻略-真是必备存在有挂暗藏猫腻,小编详细说明...
透视科普!wepoker透视方... 透视科普!wepoker透视方法(透视)hhpoker辅助,教程手筋(新版有挂)-哔哩哔哩一、wep...
wepokerplus开挂!p... wepokerplus开挂!pokemmo手机脚本(透视)脚本-其实教你是真的挂1、点击下载安装,p...
透视分享!wepoker手机版... 透视分享!wepoker手机版辅助(透视)wepoker看底牌,教程绝活(了解有挂)-哔哩哔哩1、点...