https://kotlinlang.org logo
#getting-started
Title
# getting-started
e

Eric Boggs

11/19/2021, 8:14 PM
Hey all, I'm new to Kotlin and need some help understanding. I have a String that I need to break up in to chunks of 500 or so and pass to a suspending function of a library in the correct order. However, I'm having issues because .chunked isn't suspending. So, I attempted to use runBlocking, but I think that's causing threading problems because I can't seem to observe the result. Is there some established pattern to do this or am I completely off base here? Forgive my lack of knowledge. Any help or resources you can provide would be great. Here's an example of what I was thinking initially
Copy code
fun main() {
    // fake key
    val key: String = "N39w7DKQplfbMH6dD3WJQDG7SnR0QTznHTPn04F73TOxePLIZS924FGLszocSHV70HAlnrbSuKAkoQQpgTEDANTFPvQQxpUm7bHtW91zVBfFbJZYxP79vEPUGnOGOpWkix8GTwQpInSG8jSU3hxFbQXIewT7UvNX5ZvZXkLkmKtNqb6vjNiRCtk1fWQnCsCaCUIDHkNRigOjWKES15I81oF8qgS88vNuGix4SVPzGxW1GaUuGNWyRrQ2FXy5GAxITaVQgoTmu5OIjH5hWPIGpt0CdRIJFON770iX4Rqin6utcKZiainwC7rhuRsZw5zhO2uSA1di3ucGd2VeLgCcBnnJghZfCLioyUSPq4cImsmm3PWmo0CSAe7bJEKxvzTwoPsXRC8vuMSr9EpPRBudhvn0xGSB98MEC6ADao07cp8mIXJy9EDQofUddtutsAesg5jhSkN8N1yTg8CwcpXDFckgTZ2jV91iZjNhByY0pAaafg7d4esNLhbLTJCHV8Jq3Txen1rNOYkjfKlZfwolxprIYcKaPqYNkXnufutDGhEBaJFjXwO4en2G0RUMIBiWo2XhnjQjPs6YbLgQbwSmTewPzL8w4INbbGVxtLRdkNSnfOCT94WEBh3G2D5g26rdeFWhgEDehGIiyV0gpQuJahSpB29HJkV1SFcCA56nTNhpevffPJWyqvAMJMDChqnwE43MV04dhD1pbpE1UAix4lk5S3jEumwTZ8uDItgVuXGktqlRZkG2hMSYihHrpJyJCD6TwvYzHyydq505cY8Nhrexl4vZVgT24EikGvL6CDFBoCLJUgB2tg7maRoSbxOKHgSi3Sw9YSXo0JHBpfq3IePjTPjlW4a7TFD0w4pplFjr1IQBejxNcxfwMtjz2WTq2CbFkf9n5fvpXjMU8EFXCw0ODqsoNyWAJ02T7rNCBJM7p69fViXT2AVb5Y39bKPOXUBpZxeeOpaMX1nw93lUwbuXkMemwPlJYtcEqANb"
    key.chunked(500) {
        write(it)
    }
}

suspend fun write(key: CharSequence) {
    // Write the key in order
}
j

Joffrey

11/19/2021, 8:26 PM
You're using the overload of
chunked
that takes a transformation lambda (and indeed that lambda is not suspending). You don't need to do this, you can use the
chunked
overload that builds a list of strings. Then
forEach
on a list is an inline function, which means you can use suspending functions in the lambda:
Copy code
key.chunked(500).forEach {
    write(it)
}
🙌 1
If building a whole
List<String>
from the initial string is too much (I doubt it, but assuming it were), you can use
chunkedSequence
instead, which is "lazy":
Copy code
key.chunkedSequence(500).forEach {
    write(it)
}
e

Eric Boggs

11/19/2021, 9:22 PM
Ahhhhh, thanks so much. I just wasn't paying attention apparently.