Skip to content

Commit bc58361

Browse files
committed
feat: add updateWith to FeedData for smarter updates
1 parent b53f110 commit bc58361

File tree

3 files changed

+35
-5
lines changed

3 files changed

+35
-5
lines changed

packages/stream_feeds/lib/src/models/feed_data.dart

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,28 @@ extension FeedResponseMapper on FeedResponse {
145145
);
146146
}
147147
}
148+
149+
/// Extension functions for [FeedData] to handle common operations.
150+
extension FeedDataMutations on FeedData {
151+
/// Updates this feed with new data while preserving own data.
152+
///
153+
/// Merges [updated] feed data with this instance, preserving [ownCapabilities],
154+
/// [ownMembership], and [ownFollows] from this instance when not provided. This
155+
/// ensures that user-specific data is not lost when updating from WebSocket events.
156+
///
157+
/// Returns a new [FeedData] instance with the merged data.
158+
FeedData updateWith(
159+
FeedData updated, {
160+
List<FeedOwnCapability>? ownCapabilities,
161+
FeedMemberData? ownMembership,
162+
List<FollowData>? ownFollows,
163+
}) {
164+
return updated.copyWith(
165+
// Preserve own data from the current instance if not provided
166+
// as they may not be reliable from WS events.
167+
ownCapabilities: ownCapabilities ?? this.ownCapabilities,
168+
ownMembership: ownMembership ?? this.ownMembership,
169+
ownFollows: ownFollows ?? this.ownFollows,
170+
);
171+
}
172+
}

packages/stream_feeds/lib/src/state/feed_list_state.dart

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,12 @@ class FeedListStateNotifier extends StateNotifier<FeedListState> {
4545

4646
/// Handles updates to a specific feed.
4747
void onFeedUpdated(FeedData feed) {
48-
final updatedFeeds = state.feeds.map((it) {
49-
if (it.fid.rawValue != feed.fid.rawValue) return it;
50-
return feed;
51-
}).toList();
48+
final updatedFeeds = state.feeds.sortedUpsert(
49+
feed,
50+
key: (it) => it.fid.rawValue,
51+
compare: feedsSort.compare,
52+
update: (existing, updated) => existing.updateWith(updated),
53+
);
5254

5355
state = state.copyWith(feeds: updatedFeeds);
5456
}

packages/stream_feeds/lib/src/state/feed_state.dart

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -341,8 +341,11 @@ class FeedStateNotifier extends StateNotifier<FeedState> {
341341

342342
/// Handles updates to the feed state when the feed is updated.
343343
void onFeedUpdated(FeedData feed) {
344+
final currentFeed = state.feed;
345+
final updatedFeed = currentFeed?.updateWith(feed) ?? feed;
346+
344347
// Update the feed data in the state
345-
state = state.copyWith(feed: feed);
348+
state = state.copyWith(feed: updatedFeed);
346349
}
347350

348351
/// Handles updates to the feed state when a follow is added.

0 commit comments

Comments
 (0)