I need some introduction into more advanced parts ...
# coroutines
i
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
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
As I said this is simplified version of the problem, so let’s assume we are getting data from 3 ViewModels 😉
r
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
I will check it out. Thx @rocketraman
r
@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
You can use channel for that. If you want to cache result, you also can use Deffered as container
👍 1