Junior — Middle
How to implement functionality that allows users to subscribe to updates from other users?
sobes.tech AI
Answer from AI
To implement the functionality of users subscribing to each other, you can use a data structure that stores the relationships between users — who follows whom. In Python, this is often implemented through subscription tables in databases or through dictionaries/sets in memory.
Example in Python using a dictionary, where the key is the user and the value is a set of users they follow:
class SubscriptionService:
def __init__(self):
self.subscriptions = {} # {user_id: set of user_ids}
def subscribe(self, follower_id, followee_id):
if follower_id == followee_id:
return # cannot subscribe to oneself
self.subscriptions.setdefault(follower_id, set()).add(followee_id)
def unsubscribe(self, follower_id, followee_id):
if follower_id in self.subscriptions:
self.subscriptions[follower_id].discard(followee_id)
def get_followees(self, user_id):
return self.subscriptions.get(user_id, set())
# Usage
service = SubscriptionService()
service.subscribe('user1', 'user2')
service.subscribe('user1', 'user3')
print(service.get_followees('user1')) # {'user2', 'user3'}
In a real application, a database with a subscriptions table is usually used, where each record contains follower_id and followee_id. This allows for efficient storage and querying of subscriptions.