-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbehavior_subject.c
66 lines (59 loc) · 1.97 KB
/
behavior_subject.c
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
#include "behavior_subject.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INITIAL_CAPACITY 1
void init_behavior_subject(BehaviorSubject *subject, const char *initial_value) {
subject->capacity = INITIAL_CAPACITY;
subject->subscribers = malloc(subject->capacity * sizeof(subscriber_cb));
if (subject->subscribers == NULL) {
perror("Failed to allocate memory for subscribers");
exit(EXIT_FAILURE);
}
subject->value = m_strdup(initial_value);
if (subject->value == NULL) {
perror("Failed to allocate memory for initial value");
free(subject->subscribers);
exit(EXIT_FAILURE);
}
subject->subscriber_count = 0;
}
void subscribe(BehaviorSubject *subject, subscriber_cb callback) {
subject->subscribers = realloc(subject->subscribers, (subject->subscriber_count + 1) * sizeof(subscriber_cb));
if (subject->subscribers == NULL) {
perror("Failed to allocate memory for subscribers");
exit(EXIT_FAILURE);
}
subject->subscribers[subject->subscriber_count] = callback;
subject->subscriber_count++;
// Immediately emit the current value to the new subscriber
callback(subject->value);
}
void next(BehaviorSubject *subject, const char *new_value) {
free(subject->value);
subject->value = m_strdup(new_value);
if (subject->value == NULL) {
perror("Failed to allocate memory for new value");
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < subject->subscriber_count; i++) {
subject->subscribers[i](subject->value);
}
}
void unsubscribe(BehaviorSubject *subject) {
free(subject->subscribers);
free(subject->value);
subject->subscribers = NULL;
subject->value = NULL;
subject->subscriber_count = 0;
subject->capacity = 0;
}
char *m_strdup(const char *s) {
size_t len = strlen(s) + 1;
char *new_s = malloc(len);
if (new_s == NULL) {
return NULL;
}
memcpy(new_s, s, len);
return new_s;
}