https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

janvladimirmostert

10/24/2020, 2:49 PM
i have a suspend method that i want to make use of
Copy code
suspend fun lookupListings(): List<QueryListings.SelectListingsResult> {
if i make use of runBlocking, i'm assuming it's physically blocking a thread until that suspend function completes, what is the better route to take here to get rid of the `runBlocking`s?
Copy code
class HomePage : PageResponse(
	title = "Page Title",
	description = "Page Description",
) {

	val listings = runBlocking {
		lookupListings()
	}

    val somethingElse = runBlocking {
        suspendLookupSomethingElse()
    }
Edit: this is on the JVM
w

william

10/24/2020, 4:15 PM
if you need it instantly it would have to be
runBlocking
. otherwise, you need some coroutine scope to execute the suspend function that isn't blocking. it depends how those values in
HomePage
are being used
j

janvladimirmostert

10/24/2020, 4:16 PM
i'm building an html document using those listings
Copy code
Box {
				Grid {
					listings.forEach { listing ->
						ListingItem {
							+(listing.listingTitle ?: "")
						}
					}
				}
			}
ok, so i guess that means i'll need to go suspend all the way to the main function otherwise runBlocking
w

william

10/24/2020, 4:19 PM
are you generating static html to export or is this like a web server thing?
j

janvladimirmostert

10/24/2020, 4:20 PM
that's correct, i'm building a server-side rendered page which is including data from a DB
data from the DB is being pulled using Jasync which returns a future which i converted to a coroutine using Deferred
serving the HTML page is being done with VertX which is not using Coroutines, but is doing so in an async way as well, so i need to get this generated html to VertX without blocking
w

william

10/24/2020, 4:26 PM
is this html being generated on the fly (per request) or statically all at once?
j

janvladimirmostert

10/24/2020, 4:26 PM
the whole document is generated all at once (home page -> generate home page html, contact page -> generate contact page html) ah, sorry, i misunderstood, yes, it's on the fly per request
w

william

10/24/2020, 4:28 PM
i'm not too sure how vertx ties in here but if i was thinking about ktor since requests are all suspend funs anyway i would make the whole chain suspend in your case i'm really not sure what is best
j

janvladimirmostert

10/24/2020, 4:30 PM
i guess i'll just need to experiment, this is probably more complicated than it needs to be
thanks for the input though
👍 1
VertX has a conversion kit to make it work just like Ktor: https://vertx.io/docs/vertx-lang-kotlin-coroutines/kotlin/ this should simplify things a bit if the webserver already supports Coroutines instead of trying to jump around between Coroutines, Futures and callbacks
w

william

10/25/2020, 2:22 PM
awesome thats great
2 Views