Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
Inappropriate blocking method call output stream write

I am using BufferedOutputStream

suspend fun write(byteArray: ByteArray) {    
        bos.write(byteArray)
}

But when I add suspend keyword I got warning:

Inappropriate blocking method call

What is the correct way to use output stream with coroutines?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

In general if there is a truly async alternative, it better suits the coroutines model. You could find callback-based APIs and wrap them into suspend functions using suspendCoroutine or suspendCancellableCoroutine.

However, more often than not, you need to deal with actual blocking IO.

In that case, the easiest is to simply run the blocking IO on the IO dispatcher using withContext(Dispatchers.IO):

suspend fun write(byteArray: ByteArray) = withContext(Dispatchers.IO) {    
    bos.write(byteArray)
}

However, you have to think about which level you're using the IO dispatcher at. If this method is quite low-level, maybe you should use withContext higher in the call stack, and just keep this method non-suspend.

over 4 years ago · Santiago Trujillo Report

0

OutputStream.write is a blocking function, and by convention suspend functions must never block. You can wrap it in withContext so it uses the IO dispatcher to do it appropriately. However, it is possible this won't make the warning go away because the Kotlin lint is kind of buggy about false positives for this issue.

suspend fun write(byteArray: ByteArray) = withContext(Dispatchers.IO) {    
    bos.write(byteArray)
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!