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

Icaro Temponi

11/19/2018, 7:43 PM
Thank you @jw, with your extension plus this one:
Copy code
suspend fun suspendCoroutineWithoutReturn(fn: (Continuation<Unit>) -> Unit) = suspendCoroutine(fn)
I was able to get exactly what i wanted:
Copy code
suspend fun <T : AppCompatActivity> T.awaitRunOnUi(fn: T.() -> Unit) {
    suspendCoroutineWithoutReturn { continuation ->
        runOnUiThread {
            fn()
            continuation.resume()
        }
    }
}
l

louiscad

11/19/2018, 7:50 PM
@Icaro Temponi Why don't you just use
withContext(Dispatchers.Main) { ... }
?
i

Icaro Temponi

11/19/2018, 7:53 PM
well... I don't know xD, I really should, ty, how could i forget about that
Thank you for pointing that out @louiscad that definitely simplified my code and i even made a function to further reduce it (for espresso):
Copy code
suspend fun <T> onUi(fn: suspend CoroutineScope.() -> T): T =
        withContext(Dispatchers.Main, fn)
l

louiscad

11/20/2018, 10:54 AM
@Icaro Temponi You can make it inline (with noinline lamba parameter) to avoid overhead
i

Icaro Temponi

11/20/2018, 10:55 AM
oh, i see, i'll do it, thanks again 🙂
Copy code
suspend inline fun <T> onUi(noinline fn: suspend CoroutineScope.() -> T): T =
        withContext(Dispatchers.Main, fn)
Something like this?
l

louiscad

11/20/2018, 6:48 PM
Yes. You can also rename
fn
to
block
for more consistency regarding kotlinx.coroutines
i

Icaro Temponi

11/20/2018, 8:56 PM
Ok, thanks again 😉
5 Views