Bloc Pattern: Every screen gets its own bloc?
Asked Answered
H

1

8

I am learning the bloc pattern for Flutter and there seems to be a recurring piece of advice that "every screen should have its own bloc".

But what if you queried your server for data that will be used in more than one screen? It seems redundant, and even wasteful, to hit the server several times for the same piece of data, especially if you know that data has not changed (for example, when no operations that mutate/update it have been used).

Is there anyway you can hold that data somehow to reuse it? Is it a good idea to store data used this way at the repository level? Or is this just an accepted cost of using blocs?

Hahn answered 24/1, 2020 at 0:47 Comment(0)
L
5

Architecture decisions are always highly opinionated and there is no silver bullet.

Well, here you go.


Is there anyway you can hold that data somehow to reuse it?

Offcource yes. You can architect your app like the following way.

Widgets -> Bloc -> Repository -> Local database/ Remote API

So, your bloc will never make any API call directly, but your repo layer will do. Hence, repo layer can decide whether to fetch the data from remote API or local DB or even from the in memory cache. That way, you can reuse the already cached data on multiple screens of your app.

The interesting part is that, unit testing your code will be super easy if you architect your app like this way.


Is it a good idea to store data used this way at the repository level?

Yes.

Ludie answered 24/1, 2020 at 6:13 Comment(3)
Thanks for responding. In your outline, it seems, the bloc would be responsible for adding sinks after calling some function in the repo (which would check the local DB first and only hit the server if necessary) and then store the data within the repo? Would you then cache the data in the repo and make it accessible without the use of streams? You're right when you say it's highly opinionated, one article led me to believe the bloc itself should be used as a caching layer. I just wish there was a more definitive guide to the pattern itself.Hahn
@MatthewLerner I have done several big projects using this pattern and I can assure you that it will scale very much with the projects. If you have anymore architecture related questions, feel free to post it here on stack overflow case by case so that we can help.Ludie
@MatthewLerner Yes, you can cache data on the DB and avoid calling the server again and again if you want that kind of offline functionality.Ludie

© 2022 - 2024 — McMap. All rights reserved.