Do you have to manually dispose streams from a streamprovider in Flutter?

泪湿孤枕 提交于 2021-02-07 19:16:51

问题


I can't find this in the official documentation for the provider package, does streamprovider automatically handle disposing of streams they are providing or do you have to do this manually? If so, what is the best practice of where to dispose a stream exposed using stream provider?


回答1:


No, it is not necessary to manually clean up streams when using StreamProvider.

StreamProvider extends DeferredInheritedProvider, whose documentation states that the object being listened to will be automatically disposed of when the DeferredInheritedProvider is removed from the tree.

Actually, assuming that you're not making the Stream yourself, then there is not much you can do in terms of cleaning up the actual Stream, as explained in this GitHub comment. The library providing the Stream should clean up the Stream. If, for example, I am listening to a Stream from the Firebase Auth plugin about users signing in and signing out of my app, it is the responsibility of that plugin to clear up that stream.

However, the thing listening to a Stream (StreamProvider in this case) does have a responsibility to clean up its StreamSubscription to that Stream, which StreamProvider does.

You can see in the Provider's source code here that when creating an instance of DeferredStartListening, listen is called against the stream, which returns a StreamSubscription. At the end of the method, cancel is invoked against that subscription, which cleans up the StreamSubscription.



来源:https://stackoverflow.com/questions/60777964/do-you-have-to-manually-dispose-streams-from-a-streamprovider-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!