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

igor.wojda

11/18/2018, 2:58 PM
I need some introduction into more advanced parts of coroutines. Just for simplicity let’s assume that we have 3 views that are retrieving the same data from repository (so 3 views are calling the same repository method at the same time). This repository method under the hood makes a network call, so we don’t want to make multiple requestes:
Copy code
View1 calls repos.getData() - start downloading data
View2 calls repos.getData() - data download in progress so just wait for result
View2 calls repos.getData() - data download in progress so just wait for result
How this can be achieved?
t

Tolriq

11/18/2018, 4:15 PM
Don't request data from the view 😉 Use presenter / view model or anything to do it the other way around. Current way is often via viewmodel and livedata on Android.
i

igor.wojda

11/18/2018, 5:04 PM
As I said this is simplified version of the problem, so let’s assume we are getting data from 3 ViewModels 😉
r

rocketraman

11/18/2018, 5:38 PM
You could create an actor that is responsible for retrieving the data, and storing it as actor state. When a new request arrives you just check if the previously retrieved data is stale or not, and redo the query if it is, otherwise just return it. Read the shared mutable state section of the coroutines guide: https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/shared-mutable-state-and-concurrency.md#shared-mutable-state-and-concurrency
i

igor.wojda

11/18/2018, 6:05 PM
I will check it out. Thx @rocketraman
r

rocketraman

11/18/2018, 7:07 PM
@igor.wojda Let me know if it works out... I've used Akka actors extensively but I've not had occasion to use Kotlin coroutine actors yet.
👍 1
g

gildor

11/18/2018, 8:24 PM
You can use channel for that. If you want to cache result, you also can use Deffered as container
👍 1
4 Views