Skip to content

Instantly share code, notes, and snippets.

View nsomar's full-sized avatar

Omar Abdelhafith nsomar

View GitHub Profile
@nsomar
nsomar / DiskWriteAsyncAction.swift
Created August 16, 2017 09:53
AsyncAction implementation for Suas that write to disk in the background
/// Callback called when Disk IO write operation completes
public typealias DiskWriteActionCompletionBlock = (Bool, DispatchFunction) -> Void
/// Disk Write `AsyncAction` implementation to write data to the disk asynchronously. Requires `AsyncMiddleware` to be added to the store.
///
/// # Example
///
/// ```
/// let action = DiskWriteAsyncAction(path: ..., data: ...) { succeeded, dispatch in
@nsomar
nsomar / DiskReadAsyncAction.swift
Created August 16, 2017 09:52
AsyncAction implementation for Suas that read from disk in the background
/// Callback called when Disk IO read operation completes
public typealias DiskReadActionCompletionBlock = (Data?, DispatchFunction) -> Void
/// Disk Read `AsyncAction` implementation to read data from the disk asynchronously. Requires `AsyncMiddleware` to be added to the store.
///
/// # Example
///
/// ```
/// let action = DiskReadAsyncAction(path: ...) { data, dispatch in
@nsomar
nsomar / URLSessionAsyncAction.swift
Created August 16, 2017 09:50
AsyncAction implementation for Suas that performs a URL request
/// Callback called when URLSession operation completes
public typealias URLSessionActionCompletionBlock = (Data?, URLResponse?, Error?, DispatchFunction) -> Void
/// URL Session `AsyncAction` implementation to fetch data from the network asynchronously. Requires `AsyncMiddleware` to be added to the store.
///
/// # Example
///
/// ```
/// let action = URLSessionAsyncAction(url: ...) { data, response, error, dispatch in
{^ref, reply} ->
Process.demonitor(ref, [:flush])
reply
def await(%Task{ref: ref} = task, timeout) do
receive do
{^ref, reply} ->
Process.demonitor(ref, [:flush])
reply
{:DOWN, ^ref, _, proc, reason} ->
exit({reason(reason, proc), {__MODULE__, :await, [task, timeout]}})
after
timeout ->
Process.demonitor(ref, [:flush])
def async(mod, fun, args) do
mfa = {mod, fun, args}
owner = self()
pid = Task.Supervised.spawn_link(owner, get_info(owner), mfa)
ref = Process.monitor(pid)
send(pid, {owner, ref})
%Task{pid: pid, ref: ref, owner: owner}
end
task = Task.async(fn -> Utilities.write(content, "/etc/some/secret/location") end)
Task.await(task)
defmodule Website do
def cool_api_endpoint(conn, content) do
# some calculations
# Using task
task = Task.async(fn -> Utilities.write(content, "/etc/some/secret/location") end)
json(conn, %{"result" => "success"})
end
end
defmodule Website do
def index(conn, content) do
# some calculations
Utilities.write(content, "/etc/some/secret/location")
# Receving the sent message
receive do
result -> # use the result
end
defmodule Utilities do
def write(content, file) do
# get th target process
target = self()
spawn(fn ->
# write stuff to disk
# takes long time