what’s the recommended way of doing something like...
# coroutines
m
what’s the recommended way of doing something like this:
Copy code
fun refreshData() {
        networkStatus = Status.ACTIVE // class member
        launch(CommonPool) {
            asyncAwait {
                remoteSource.fetchData().forEach {
                    roomDatabase.dao().insertData(it)
                }
                networkStatus = Status.INACTIVE
            }
        }
    }
i’d like to be able to unit test that the status is updated while the coroutine is running
having a channel will make it much easier to be notified when the status changes
and conflated channels only have the most recent value
d
are you looking for this:
Copy code
runBlocking {
    remoteSource.fetchData().forEach {
        roomDatabase.dao().insertData(it)
    }
    networkStatus = Status.INACTIVE
}
it doesn't make very much sense to do this when you're already in a coroutine/suspend function, though. You can just inline the code..
Alternatively,
Copy code
launch { 
    // code here
}.join()
g
What is
asyncAwait
? Shortcut for async{}.await()? If so, it doesn’t make any sense, there are not cases when you call async{} and await immidiately. Probably you can just call the function or use withContext instead
1
also
CommonPool
in probably redundant
In general such function is actually bad style in most cases, instead function should be suspend without
launch(CommonPool)
and
asyncAwait
so it allows you to wait (suspend) until function finish and check side effect after It’s exactly the same bad style as launch thread in a function: you just cannot test it and have other problems with lifecycle of such function, concurrent updates and so on
One more issue with your code, that your Room method calls are blocking, so you block threads from CommonPool and it’s not good and can cause deadlocks and general performance problems with coroutine dispatching. I recommend to wrap such calls to new IO coroutine dispatcher (like
withContext(IO)
). or use async API of Room (there are adapters for RxJava and LiveData)
https://kotlinlang.slack.com/archives/C1CFAFJSK/p1536267046000100?thread_ts=1536257585.000100&cid=C1CFAFJSK What is use case for such idiom? If you already inside coroutine (can use join), you don’t need launch, use withContext instead
d
Yeah, you are right. I was a bit confused by the question myself.
^^^ He brought up some good points