| 1 |
#define REACTIVE |
| 2 |
using System; |
| 3 |
using System.Collections.Generic; |
| 4 |
using System.IO; |
| 5 |
using System.Linq; |
| 6 |
using System.Json; |
| 7 |
using System.Net; |
| 8 |
using System.Reactive; |
| 9 |
using System.Reactive.Linq; |
| 10 |
|
| 11 |
using Android.App; |
| 12 |
using Android.Content; |
| 13 |
using Android.Runtime; |
| 14 |
using Android.Views; |
| 15 |
using Android.Widget; |
| 16 |
using Android.OS; |
| 17 |
|
| 18 |
namespace GithubApiClientSample |
| 19 |
{ |
| 20 |
[Activity (Label = "GithubApiClientSample", MainLauncher = true)] |
| 21 |
public class MainActivity : ListActivity |
| 22 |
{ |
| 23 |
protected override void OnCreate (Bundle bundle) |
| 24 |
{ |
| 25 |
base.OnCreate (bundle); |
| 26 |
|
| 27 |
var baseDir = Path.Combine (Application.ApplicationInfo.DataDir, "image_cache"); |
| 28 |
if (!Directory.Exists (baseDir)) |
| 29 |
Directory.CreateDirectory (baseDir); |
| 30 |
|
| 31 |
var data = new List<IDictionary<string,object>> (); |
| 32 |
var urls = new Dictionary<Uri,List<string>> (); |
| 33 |
var getUrl = new Uri ("https://api.github.com/users/mono/repos"); |
| 34 |
var hr = new HttpWebRequest (getUrl); |
| 35 |
var req = Observable.FromAsyncPattern<WebResponse> (hr.BeginGetResponse, hr.EndGetResponse); |
| 36 |
Observable.Defer (req).Subscribe (v => { |
| 37 |
var json = (IEnumerable<JsonValue>) JsonValue.Load (v.GetResponseStream ()); |
| 38 |
json.Cast<JsonObject> ().ToList ().ForEach (item => { |
| 39 |
var uri = new Uri ((string) ((JsonObject) item ["owner"])["avatar_url"]); |
| 40 |
var file = Path.Combine (baseDir, ((int) item ["id"]) + new FileInfo (uri.LocalPath).Extension); |
| 41 |
if (!urls.ContainsKey (uri)) |
| 42 |
urls.Add (uri, new List<string> () {file}); |
| 43 |
else |
| 44 |
urls [uri].Add (file); |
| 45 |
data.Add (new JavaDictionary<string,object> () { {"Text", item ["description"]}, {"Name", item ["name"]}, {"Icon", Path.Combine (baseDir, file) }}); |
| 46 |
urls.ToList ().ForEach (p => { |
| 47 |
var iwc = new WebClient (); |
| 48 |
iwc.DownloadDataCompleted += (isender, ie) => p.Value.ForEach (s => { |
| 49 |
if (ie.Result != null) |
| 50 |
using (var fs = File.Create (s)) |
| 51 |
fs.Write (ie.Result, 0, ie.Result.Length); |
| 52 |
}); |
| 53 |
iwc.DownloadDataAsync (p.Key); |
| 54 |
}); |
| 55 |
}); |
| 56 |
|
| 57 |
var from = new string [] {"Text", "Name", "Icon"}; |
| 58 |
var to = new int [] { Resource.Id.textMessage, Resource.Id.textName, Resource.Id.iconView}; |
| 59 |
|
| 60 |
this.RunOnUiThread (() => { |
| 61 |
ListAdapter = new SimpleAdapter (this, data, Resource.Layout.ListItem, from, to); |
| 62 |
}); |
| 63 |
}); |
| 64 |
} |
| 65 |
} |
| 66 |
} |