matt tighe
01/18/2019, 5:41 PMval liveData: LiveData<List<Thing>> = myDao.getAllThings()
val mediator = MediatorLiveData<Things>
fun startObservation() {
mediator.addSource(liveData) { it?.let { newThings->
sendThingsOverNetwork(newThings)
}
}
suspend fun sendThingsOverNetwork = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
// Do network ops off main thread
}
Allan Wang
01/18/2019, 5:42 PMmatt tighe
01/18/2019, 5:44 PMAllan Wang
01/18/2019, 5:47 PMscope.launch { sendThingsOverNetwork(newThings) }
, where scope is your current scope. The problem is that you might be dealing with backpressure, in that the data you observe occurs faster than you can handle it. In that case, you can use a channel to queue requests, or use a conflated channel to only keep the latest request while you handle previous ones. You would start handling the channel using
launch {
for (thing in channel) {
...
}
}
And you can send 'things' to channel via offer
or send
, depending on your needsmatt tighe
01/18/2019, 5:50 PMscope
need to be coroutine scope? It doesn’t seem like there is a coroutine scope in observersAllan Wang
01/18/2019, 5:51 PMmatt tighe
01/18/2019, 6:00 PMghedeon
01/18/2019, 7:48 PMmatt tighe
01/18/2019, 8:09 PMghedeon
01/18/2019, 8:33 PMmatt tighe
01/18/2019, 8:48 PMval coroutineScope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
coroutineScope.launch { executeNetworkRequest }
Would using the viewmodel scope benefit me at all?ghedeon
01/18/2019, 9:09 PMonCleared
. It all makes sense if you think about it, with lifecycle and stuff.matt tighe
01/18/2019, 9:21 PMinit {
mediator.addSource(source) {
callLaunchingFunction()
}
}
public fun submitEvent() {
callLaunchingFunction()
}
private fun callLaunchingFunction() {
val coroutineScope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
coroutineScope.launch { myObject.suspendingFunction() }
}
Trying to use mockito to verify myObject.suspendingFunction()
will fail randomly, because I haven’t found a way to guarantee the launch of the coroutine in callLaunchingFunction()
yet. Turning it into a suspending function and launching from a higher level would work in the case of calling submitEvent
but doesn’t solve the issue of when the observer calls it.