-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostStream.cs
More file actions
71 lines (60 loc) · 2.24 KB
/
PostStream.cs
File metadata and controls
71 lines (60 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
namespace Project3
{
internal class PostStream : IObservable<string>
{
// reactive programming
private readonly IScheduler scheduler;
private ISubject<string> postSubject;
public string UserAgent { get; set; }
public string Token { get; set; }
public PostStream(string userAgent, string token)
{
postSubject = new Subject<string>();
scheduler = new EventLoopScheduler();
UserAgent = userAgent;
Token = token;
}
public async Task GetSubredditPosts(string subredditName)
{
string responseBody;
List<string> posts = new List<string>();
string url = $"https://oauth.reddit.com/r/{subredditName}/new.json";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
client.DefaultRequestHeaders.Add("User-Agent", $"{UserAgent}");
try
{
var response = await client.GetAsync(url);
responseBody = await response.Content.ReadAsStringAsync();
client.Dispose();
// extracting post id's
JObject responseJson = JObject.Parse(responseBody);
JArray children = (JArray)responseJson["data"]!["children"]!;
foreach (JToken child in children)
{
JObject postData = (JObject)child["data"]!;
string name = (string)postData["name"]!;
if (name != "")
{
postSubject.OnNext(name!);
}
}
postSubject.OnCompleted();
}
catch (Exception ex)
{
postSubject.OnError(ex);
}
}
public IDisposable Subscribe(IObserver<string> observer)
{
return postSubject.ObserveOn(scheduler).Subscribe(observer);
//return postSubject.Subscribe(observer);
}
}
}