Created
March 4, 2019 06:50
-
-
Save yshrsmz/3f2df32562bc72cea08bdea7bdb5e76e to your computer and use it in GitHub Desktop.
SQLDelight Kotlin Multiplatform Project sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| internal expect fun <B> backToFront(b: () -> B, job: (B) -> Unit) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private val btfHandler = Handler(Looper.getMainLooper()) | |
| internal actual fun <B> backToFront(b: () -> B, job: (B) -> Unit) { | |
| btfHandler.post { job(b()) } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| internal actual fun <B> backToFront(b: () -> B, job: (B) -> Unit) { | |
| dispatch_async_f( | |
| dispatch_get_main_queue(), | |
| DetachedObjectGraph { JobAndThing(job.freeze(), b()) }.asCPointer(), | |
| staticCFunction { p: COpaquePointer? -> | |
| initRuntimeIfNeeded() | |
| @Suppress("UNCHECKED_CAST") val result = DetachedObjectGraph<Any>(p).attach() as JobAndThing<B> | |
| result.job(result.thing) | |
| }) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import com.codingfeline.github.platform.backToFront | |
| import com.squareup.sqldelight.Query | |
| import kotlinx.coroutines.ExperimentalCoroutinesApi | |
| import kotlinx.coroutines.channels.Channel | |
| import kotlinx.coroutines.channels.consumeEach | |
| import co.touchlab.stately.concurrency.ThreadLocalRef | |
| @ExperimentalCoroutinesApi | |
| fun <T : Any> Query<T>.asChannel(): ReceiveChannel<Query<T>> { | |
| val channel = Channel<Query<T>>(Channel.CONFLATED) | |
| channel.offer(this) | |
| val ref = ThreadLocalRef<(Query<T>) -> Unit>() | |
| ref.set { channel.offer(it) } | |
| val listener = object : Query.Listener, (Throwable?) -> Unit { | |
| override fun queryResultsChanged() { | |
| backToFront({ this@asChannel }, { q -> ref.get()?.let { it(q) } }) | |
| } | |
| override fun invoke(t: Throwable?) { | |
| ref.remove() | |
| removeListener(this) | |
| } | |
| } | |
| addListener(listener) | |
| channel.invokeOnClose(listener) | |
| return channel | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment