D-James-GH / cached_query

Simple caching for flutter apps
MIT License
47 stars 10 forks source link

How can i use stream in UI? #4

Closed Arjun544 closed 1 year ago

Arjun544 commented 1 year ago

I'm making a function that emits data, so i want to listen and update UI

Here is my function that returns stream:

static final currentProfileQuery = Query<Stream<ProfileModel>>( key: CachingKeys.currentProfileKey, queryFn: () async => await UserServices.getCurrentProfile(profile: 'fun'), );

How can I use this function in UI? The return type of 'currentProfileQuery.stream" is Stream<QueryState<Stream<ProfileModel>>>

D-James-GH commented 1 year ago

Hi Arjun, Cached query has been designed to cache the results of futures rather than streams, however, I am open to suggestion if you can explain your current requirements further. A Query will cache whatever is returned from the queryFn, for this reason it is probably not advisable to return a stream and only return data. Where does the stream originate? if it is firebase then it is unlikely you will need CachedQuery for the current profile call as firebase does a good job of caching. If not from firebase is there a reason the UserService is returning a stream?

If it does need to be a stream and you would like to cache the values using cached query I would suggest updating the global cache inside a stream listener. For example:

// first get the current profile as a future 
final currentUser = Query<ProfileModel>(
    key: CachingKeys.currentProfileKey,
    queryFn: () async => // return a ProfileModel
);

// Then update that query using data from the user stream
UserServices.getCurrentProfile(profile: 'fun').listen((profile) {
   CachedQuery.instance.updateQuery<ProfileModel>(
      key: CachingKeys.currentProfileKey,
      updateFn: (old) => profile, // return the new profile, this will update the profile query
    );
});