Skip to content

Instantly share code, notes, and snippets.

@nietaki
Created October 15, 2019 21:56
Show Gist options
  • Save nietaki/6f6c78d79c915c3c2c0273c754bf6561 to your computer and use it in GitHub Desktop.
Save nietaki/6f6c78d79c915c3c2c0273c754bf6561 to your computer and use it in GitHub Desktop.
def category_preloader(category_names) when is_list(category_names) do
# category_names are already deduplicated
Enum.map(category_names, &RemoteService.retrieve_category_info/1)
end
query =
from(p in Post,
where: p.id in ^post_ids,
preload: [category: ^&category_preloader/1]
)
posts = Repo.all(query)
refute Enum.any?(posts, &(&1.category == nil))
# alternatively, concurrent version
def concurrent_category_preloader(category_names) when is_list(category_names) do
category_names
|> Enum.map(fn name -> Task.async(RemoteService, :retrieve_category_info, [name]) end)
|> Enum.map(fn task -> Task.await(task) end)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment