当我从Coroutines Flow中收集时,请发出警告?

发布于 2025-01-25 18:08:10 字数 1158 浏览 2 评论 0原文

有人可以解释为什么当我在主线程中收集时,strictmode为什么会给我警告吗?

我在应用程序类文件中启用了strictmode。

StrictMode.setThreadPolicy(
            StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork() 
                .penaltyLog()
                .build()
        )

在这里,我启动了一个从流量中收集的Coroutine。

binding.buttonOne.setOnClickListener {
    CoroutineScope(Dispatchers.Main).launch {
       simple().flowOn(Dispatchers.IO).collect {
             Log.d(TAG, "in collect block: ${Thread.currentThread().name}")
             binding.flowExampleone.text="$it"
             log(it.toString())
         }
    }
}
 fun simple() = flow<Int> {
        for (i in 1..3) {
            Log.d(TAG, "in simple block: ${Thread.currentThread().name}")
            delay(1000)
            emit(i)
        }
    }

    fun log(message: String) {
        Log.d("mytag", message)
    }

但是当我运行它时。严格模式正在发出警告。

D/StrictMode: StrictMode policy violation; ~duration=34 ms: android.os.strictmode.DiskReadViolation

Can somebody please explain why StrictMode giving me warning when I collect in Main thread?

I have strictMode enabled in my application class file.

StrictMode.setThreadPolicy(
            StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork() 
                .penaltyLog()
                .build()
        )

Here I launching a coroutine to collect from the Flow.

binding.buttonOne.setOnClickListener {
    CoroutineScope(Dispatchers.Main).launch {
       simple().flowOn(Dispatchers.IO).collect {
             Log.d(TAG, "in collect block: ${Thread.currentThread().name}")
             binding.flowExampleone.text="$it"
             log(it.toString())
         }
    }
}
 fun simple() = flow<Int> {
        for (i in 1..3) {
            Log.d(TAG, "in simple block: ${Thread.currentThread().name}")
            delay(1000)
            emit(i)
        }
    }

    fun log(message: String) {
        Log.d("mytag", message)
    }

But when i run it. The StrictMode is giving warning.

D/StrictMode: StrictMode policy violation; ~duration=34 ms: android.os.strictmode.DiskReadViolation

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文