Michał Kalinowski
07/05/2020, 3:02 PMsuspend fun fooA(){
coroutineScope {
fooB(this)
}
}
fun fooB(coroutineScope: CoroutineScope){
continueWithSuspend(coroutineScope){
continueSuspendingFooA()
}
}
private suspend fun continueSuspendingFooA(){}
Erik
07/05/2020, 4:40 PMMichał Kalinowski
07/05/2020, 7:23 PMfun <T : Any> LiveData<T>.observeWithSuspend(observer: suspend (data: T) -> Unit)
, which I could call when creating View :<, When liveData make a dispatch it would suspend the scope it is in, until all jobs are donearaqnid
07/06/2020, 9:07 AMcoroutineContext
intrinsic. A coroutine scope is essentially just a wrapper around that: CoroutineScope(coroutineContext)
Michał Kalinowski
07/06/2020, 10:19 AMsuspend fun fooA(){
coroutineScope {
println("we start here")
fooB(coroutineContext)
println("and end here after 1s :)")
}
}
fun fooB(coroutineContext: CoroutineContext){
runBlocking(coroutineContext) {
continueSuspendingFooA()
}
}
private suspend fun continueSuspendingFooA(){
delay(1000)
}
myanmarking
07/07/2020, 8:48 AMMichał Kalinowski
07/07/2020, 9:49 PM// some simplified LiveData methods(observe and observeWithSuspend) without lifecycle:
fun observe(observer: LiveDataObserver<T>) {
observers.add(observer)
}
fun <T : Any> LiveData<T>.observeWithSuspend(
context: CoroutineContext,
observer: suspend (data: T) -> Unit
) {
observe {
runBlocking(context) {
observer(it)
}
}
}
// Our viewModel
class SomeViewModel(){
val someJobScope = CoroutineScope(Dispatchers.Default)
// LiveData will block scope in a way that first will be performed points in order 1. 2. 3. 4.
val someLiveData = MutableLiveData<Position>()
//function that set our liveData
private fun handleCoordinate(position: Position) {
someJobScope.launch {
// 1.
someLiveData.value = position // 2.
// 4
}
}
}
// Our activity/fragment
class SomeActivity(){
val viewModel: SomeViewModel // our viewModel
val someCoordinator: SomeCoordinator // our coordinator that will be observed and will suspend viewModel.someJobScope when notified
override fun onViewCreated() {
viewModel.someLiveData.observeWithSuspend(viewModel.someJobScope.coroutineContext) { position ->
// 3
someCoordinator.performSomeActionWithSuspend(position) // some suspended function to work with coordinator!
}
}
}