Guest User

Untitled

a guest
Mar 23rd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.71 KB | None | 0 0
  1. static func fetchCommentsAndTheirReplies(articleId: String, failure: ((NSError)->Void)?, success: (comments: [[String: AnyObject]], replies: [[[String: AnyObject]]], userIds: Set<String>)->Void) {
  2. var retComments = [[String: AnyObject]]()
  3. var retReplies = [[[String: AnyObject]]]()
  4. var retUserIds = Set<String>()
  5.  
  6. let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
  7. Alamofire.request(.GET, API.baseUrl + API.article.listCreateComment, parameters: [API.article.articleId: articleId]).responseJSON {
  8. response in
  9.  
  10. dispatch_async(queue) {
  11.  
  12. guard let comments = response.result.value as? [[String: AnyObject]] else {
  13. failure?(Helper.error())
  14. return
  15. }
  16. print(comments)
  17. retComments = comments
  18.  
  19. let group = dispatch_group_create()
  20.  
  21. for (commentIndex, comment) in comments.enumerate() {
  22. guard let id = comment["_id"] as? String else {continue}
  23.  
  24. let relevantUserIds = helperParseRelaventUserIdsFromEntity(comment)
  25. for userId in relevantUserIds {
  26. retUserIds.insert(userId)
  27. }
  28.  
  29. retReplies.append([[String: AnyObject]]())
  30.  
  31. dispatch_group_enter(group)
  32. Alamofire.request(.GET, API.baseUrl + API.article.listCreateReply, parameters: [API.article.commentId: id]).responseJSON {
  33. response in
  34.  
  35. dispatch_async(queue) {
  36. if let replies = response.result.value as? [[String: AnyObject]] {
  37. for (_, reply) in replies.enumerate() {
  38.  
  39. let relevantUserIds = helperParseRelaventUserIdsFromEntity(reply)
  40. for userId in relevantUserIds {
  41. retUserIds.insert(userId)
  42. }
  43. }
  44. retReplies[commentIndex] = replies
  45. }
  46. dispatch_group_leave(group)
  47. }
  48.  
  49. }
  50. }
  51.  
  52. dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
  53. success(comments: retComments, replies: retReplies, userIds: retUserIds)
  54.  
  55. }
  56.  
  57. }
  58. }
  59.  
  60. public static void fetchCommentsAndTheirReplies(Context context, String articleId, final StringBuffer outErrorMessage, final Runnable failure, final ArrayList<JSONObject> outComments, final ArrayList<ArrayList<JSONObject>> outReplies, final HashSet<String> outUserIds, final Runnable success) {
  61. final RequestQueue queue = Volley.newRequestQueue(context);
  62. HashMap<String, String> commentParams = new HashMap<>();
  63. commentParams.put(API.article.articleId, articleId);
  64. JsonArrayRequest commentRequest = new JsonArrayRequest(Request.Method.GET, API.baseUrl + API.article.listCreateComment, new JSONObject(commentParams), new Response.Listener<JSONArray>() {
  65. @Override
  66. public void onResponse(JSONArray response) {
  67. try {
  68. for (int i = 0; i < response.length(); i++) {
  69. JSONObject comment = response.getJSONObject(i);
  70. outComments.add(comment);
  71.  
  72. outUserIds.addAll(helperParseRelaventUserIdsFromEntity(comment));
  73. outReplies.add(new ArrayList<JSONObject>());
  74.  
  75. //TODO: DISPATCH_GROUP?
  76. String id = comment.getString("_id");
  77. HashMap<String, String> replyParams = new HashMap<>();
  78. replyParams.put(API.article.commentId, id);
  79. final int finalI = i;
  80. JsonArrayRequest replyRequest = new JsonArrayRequest(Request.Method.GET, API.baseUrl + API.article.listCreateReply, new JSONObject(replyParams), new Response.Listener<JSONArray>() {
  81. @Override
  82. public void onResponse(JSONArray response) {
  83. try {
  84. for (int j = 0; j < response.length(); j++) {
  85. JSONObject reply = response.getJSONObject(j);
  86. outUserIds.addAll(helperParseRelaventUserIdsFromEntity(reply));
  87. outReplies.get(finalI).add(reply);
  88. }
  89. } catch (JSONException ex) {}
  90. }
  91. }, new Response.ErrorListener() {
  92. @Override
  93. public void onErrorResponse(VolleyError error) {}
  94. });
  95. queue.add(replyRequest);
  96. }
  97. success.run();
  98.  
  99. } catch (JSONException ex) {}
  100. }
  101. }, new Response.ErrorListener() {
  102. @Override
  103. public void onErrorResponse(VolleyError error) {
  104. outErrorMessage.append(error.getMessage());
  105. failure.run();
  106. }
  107. });
  108. queue.add(commentRequest);
  109. }
  110.  
  111. taskCount++;
  112. if (taskCount == totalCount) {
  113. success.run();
  114. }
  115.  
  116. public class DispatchGroup {
  117.  
  118. private int count = 0;
  119. private Runnable runnable;
  120.  
  121. public DispatchGroup()
  122. {
  123. super();
  124. count = 0;
  125. }
  126.  
  127. public synchronized void enter(){
  128. count++;
  129. }
  130.  
  131. public synchronized void leave(){
  132. count--;
  133. notifyGroup();
  134. }
  135.  
  136. public void notify(Runnable r) {
  137. runnable = r;
  138. notifyGroup();
  139. }
  140.  
  141. private void notifyGroup(){
  142. if (count <=0 && runnable!=null) {
  143. runnable.run();
  144. }
  145. }
  146. }
  147.  
  148. public void onResponse(JSONArray response) {
  149. try {
  150. final int[] taskFinished = {0};
  151. final int taskTotal = response.length();
  152. for (int i = 0; i < response.length(); i++) {
  153. JSONObject comment = response.getJSONObject(i);
  154. outComments.add(comment);
  155.  
  156. outUserIds.addAll(helperParseRelaventUserIdsFromEntity(comment));
  157. outReplies.add(new ArrayList<JSONObject>());
  158.  
  159. //TODO: DISPATCH_GROUP?
  160. String id = comment.getString("_id");
  161. HashMap<String, String> replyParams = new HashMap<>();
  162. replyParams.put(API.article.commentId, id);
  163. final int finalI = i;
  164. JsonArrayRequest replyRequest = new JsonArrayRequest(Request.Method.GET, API.baseUrl + API.article.listCreateReply, new JSONObject(replyParams), new Response.Listener<JSONArray>() {
  165. @Override
  166. public void onResponse(JSONArray response) {
  167. taskFinished[0]++;
  168. try {
  169. for (int j = 0; j < response.length(); j++) {
  170. JSONObject reply = response.getJSONObject(j);
  171. outUserIds.addAll(helperParseRelaventUserIdsFromEntity(reply));
  172. outReplies.get(finalI).add(reply);
  173. }
  174. } catch (JSONException ex) {}
  175. if (taskFinished[0] == taskTotal) {
  176. success.run();
  177. }
  178. }
  179. }, new Response.ErrorListener() {
  180. @Override
  181. public void onErrorResponse(VolleyError error) {
  182. taskFinished[0]++;
  183. if (taskFinished[0] == taskTotal) {
  184. success.run();
  185. }
  186. }
  187. });
  188. queue.add(replyRequest);
  189. }
  190.  
  191.  
  192. } catch (JSONException ex) {}
  193. }
  194.  
  195. task {
  196. //some (long running) operation, or just:
  197. 1 + 1
  198. } then {
  199. i -> "result: $i"
  200. } success {
  201. msg -> println(msg)
  202. }
  203.  
  204. val dispatchGroup = DispatchGroup()
  205. dispatchGroup.enter()
  206. // Some long running task
  207. dispatchGroup.leave()
  208.  
  209. dispatchGroup.notify {
  210. // Some code to run after all dispatch groups complete
  211. }
  212.  
  213. class DispatchGroup {
  214. private var count = 0
  215. private var runnable: (() -> Unit)? = null
  216.  
  217. init {
  218. count = 0
  219. }
  220.  
  221. @Synchronized
  222. fun enter() {
  223. count++
  224. }
  225.  
  226. @Synchronized
  227. fun leave() {
  228. count--
  229. notifyGroup()
  230. }
  231.  
  232. fun notify(r: () -> Unit) {
  233. runnable = r
  234. notifyGroup()
  235. }
  236.  
  237. private fun notifyGroup() {
  238. if (count <= 0 && runnable != null) {
  239. runnable!!()
  240. }
  241. }
  242. }
Add Comment
Please, Sign In to add comment