问题描述
我目前正在尝试更多利用kotlin协程.但是我面临一个问题:在这些协程中使用moshi或okhttp时,我会收到警告:
I am currently trying to leverage kotlin coroutines more. But I face a problem: when using moshi or okhttp inside these coroutines I get a warning:
不适当的阻止方法调用"
"inappropriate blocking method call"
解决这些问题的最佳方法是什么?我真的不想不合适;-)
What is the best way to fix these? I really do not want to be inappropriate ;-)
推荐答案
警告是关于阻塞当前线程的方法,并且协程无法正确挂起.这样,您将失去协程的所有优势,并再次将每个线程降级为一项任务.
The warning is about methods that block current thread and coroutine cannot be properly suspended. This way, you lose all benefits of coroutines and downgrade to one job per thread again.
每种情况应以不同的方式处理.对于可挂起的http呼叫,您可以使用 ktor http客户端.但是有时您的案例没有库,因此您可以编写自己的解决方案或忽略此警告.
Each case should be handled in a different way. For suspendable http calls you can use ktor http client. But sometimes there is no library for your case, so you can either write your own solution or ignore this warning.
withContext(Dipatchers.IO)
或某些自定义调度程序可用于解决此问题.感谢您的评论.
withContext(Dipatchers.IO)
or some custom dispatcher can be used to workaround the problem. Thanks for the comments.
这篇关于如何进行“不适当的阻塞方法调用"?合适的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!