https://kotlinlang.org logo
Title
g

gildor

08/15/2017, 9:29 AM
no, something like:
suspend fun Db.saveAsync() = async(DbPool) { db.save() }
db.saveAsync().await()

or 

suspend fun Db.saveAsync() = run(DbPool) { db.save() }
db.saveAsync()
q

qwert_ukg

08/18/2017, 5:46 AM
@gildor could u plz help me some more. if i want to handle saving? how i can to do this? for examle im ready to return ansver to client right after reseveving request, and then will be async saving, but after saving is complite i want to do something more with it? Its much hurder to understand for me, then callback invocation (bow)
g

gildor

08/18/2017, 5:50 AM
You have two options: 1. Return successful answer (or just Unit) or throw exception. So exactly what you have with synchronous save 2. Use some result object that has two states success (with result) and fail (with exception object). Kotlin sealed classes really good for this So, because coroutines sequential by default you just call:
db.saveAsync()
doSomethingElse()
doSomethingElse() will be called after db save will be finished
q

qwert_ukg

08/18/2017, 5:53 AM
doSomthingElse()
should be
suspend
func and should be called into async func?
g

gildor

08/18/2017, 5:54 AM
up to you
the only difference is that
saveAsync()
doesn’t lock thread from which you called it
and allows you to write code in synchronous style instead callbacks/features
q

qwert_ukg

08/18/2017, 10:24 AM
have a really strange behavior, then i call action of controller manually - from browser - saving complited normally, but if i run a tests - saveAsync will not be invoke
just modify suspend func like this
suspend fun NotificationRepository.sendAndSaveAsync(notification: Notification) = run(CommonPool) {
    with(notification) {
        messageType!!.sender.makeRequest(notification)
        responseBody = messageType!!.sender.getResponse(this)
        save(this)
    }
}!!
and invoke it like this
async(CommonPool) { saveAsync(notification) }
g

gildor

08/18/2017, 10:27 AM
If you run async() don’t forget to call .join()
Also, just general advice. Don’t use CommonPool for blocking operations. Create a separate pool for that
I don’t understand your problem about “saveAsync will not be invoke”
q

qwert_ukg

08/18/2017, 10:45 AM
then i run my tests saving is not invoied
notificationsForSendRequests.forEach {
                val json = mockMvc.perform(it)
                        .andExpect(status().isOk)
                        .andReturn().response.contentAsString
                val identifier = JsonPath.read<Long>(json, "$.identifier")
                assertTrue(identifier > 0)
but if i run app, and send a rest request - everything is fine
g

gildor

08/18/2017, 10:59 AM
I don't understand by this code fragment what's went wrong in this test code
q

qwert_ukg

08/18/2017, 11:04 AM
what di u mean "dont forget to call join()"?
async(pool) havent a job as i understand