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

sujin

11/10/2019, 10:06 AM
How to transform data using coroutines in each repository layer? Something like we do in RxJava using map or flatmap. For example, using flatmap in remote layer for converting necessary changes and use that output in data layer
g

gildor

11/10/2019, 10:22 AM
Are you talking about suspend functions? Just do transformation as with any blocking imperative code, get data, transform, save to local variable or pass directly to next step
You don't need analogue of flatMap, because you just can call suspend functions and receive result directly
s

sujin

11/10/2019, 10:27 AM
But for that do I have to call two
async
function or
withContext
? One in data layer and other in remote layer?
g

gildor

11/10/2019, 12:38 PM
I didn't get your question
If both, local and remote data available as suspend functions, just call them, get result If you want to run multiple asynchronous operations in parallel, use async to launch them and await() to get result
👍 1
Yes, but it make sense only if you work with stream of data, if you replace Rx Single you don't need Flow or flatMap
r

rkeazor

11/10/2019, 2:57 PM
I agree
s

sujin

11/11/2019, 5:51 AM
Copy code
suspend fun someDataRepositoryFunction() {
	withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
		remoteRepository.someRemoteRepositoryFetchPosts()
	}
}

suspend fun someRemoteRepositoryFetchPosts() {
	val posts = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
		apiService.fetchPost()
	}
	
	return someDataTrasformationFunction(posts)
}
What i am trying to say is, inorder to transform data in remote layer, do I have to do something like this or is there anyother better way to handle this. Notice the nested
<http://Dispatchers.IO|Dispatchers.IO>
g

gildor

11/11/2019, 6:01 AM
I'm still don't understand your question
Looks, that you don't need this withContext, because fetchPost() and someRemoteRepositoryFetchPosts() should be already suspend non blocking functions, no need to wrap them to IO (at least it's the case for properly structured asyncronous code)
also not sure "there anyother better way to handle this." what can be better? you just got result, pass it to another function, you can transform result if you want, it works as any other sequential imperative code
3 Views