Created
March 24, 2020 08:28
-
-
Save 19Site/5cde1ce53120488a14fefb98f16320cc to your computer and use it in GitHub Desktop.
Async task helper, help you the async tasks one by one.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.lib; | |
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* Async task helper | |
* Help you the async tasks one by one | |
* | |
* @author 19Site | |
* @version 1 | |
*/ | |
public class Async { | |
/** | |
* run task one by one | |
*/ | |
public static void waterfall(Tasks tasks, OnWaterfallCompleted completed) { | |
if (tasks == null) { | |
waterfall(new ArrayList<Task>(), completed); | |
} else { | |
waterfall(tasks.getAll(), completed); | |
} | |
} | |
/** | |
* run task one by one | |
*/ | |
public static void waterfall(Task[] tasks, OnWaterfallCompleted completed) { | |
if (tasks == null) { | |
waterfall(new ArrayList<Task>(), completed); | |
} else { | |
ArrayList<Task> aTasks = new ArrayList<Task>(); | |
for (Task task : tasks) { | |
aTasks.add(task); | |
} | |
waterfall(aTasks, completed); | |
} | |
} | |
/** | |
* run task one by one | |
*/ | |
public static void waterfall(final List<Task> tasks, OnWaterfallCompleted completed) { | |
// init complete | |
final OnWaterfallCompleted mCompleted = completed != null ? completed : new OnWaterfallCompleted() { | |
@Override | |
public void run(Exception ex) { | |
} | |
}; | |
// no tasks | |
if (tasks == null || tasks.size() == 0) { | |
mCompleted.run(null); | |
return; | |
} | |
// next | |
Next next = new Next() { | |
@Override | |
public void run(Exception ex) { | |
if (ex != null) { | |
mCompleted.run(ex); | |
} else if (tasks.size() == 0) { | |
mCompleted.run(null); | |
} else { | |
tasks.remove(0).run(this); | |
} | |
} | |
}; | |
// run | |
next.run(null); | |
} | |
/** | |
* task | |
*/ | |
public interface Task { | |
void run(Next next); | |
} | |
/** | |
* next | |
*/ | |
public interface Next { | |
void run(Exception ex); | |
} | |
/** | |
* on waterfall task completed | |
*/ | |
public interface OnWaterfallCompleted { | |
void run(Exception ex); | |
} | |
/** | |
* tasks collection | |
*/ | |
public static class Tasks { | |
// tasks container | |
private List<Task> tasks; | |
/** | |
* constructor | |
*/ | |
public Tasks() { | |
tasks = new ArrayList<Task>(); | |
} | |
/** | |
* add a task | |
*/ | |
public Tasks put(Task task) { | |
tasks.add(task); | |
return this; | |
} | |
/** | |
* get task by index | |
*/ | |
public Task get(int index) { | |
return tasks.get(index); | |
} | |
/** | |
* get task by index | |
*/ | |
public List<Task> getAll() { | |
return tasks; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment