2

What is the best practice to notify all the fragments that are in backstack on some change?

I try to use EventBus and every Fragment subscribe to the event, then when change is happening the main activity send post event to all the subscribers.

Only onDestroy I Unsubscribe the destroyed fragment.

I don't like this solution because if there are many fragments in backstack, it can be heavy + lots of listeners simultany.

my application, has infinity drill down, from one fragment you replace to other (and add to backstack) and you can replace again (and add to backstack) and so on..., with no end.

gprathour
  • 14,813
  • 5
  • 66
  • 90
user1245809
  • 153
  • 1
  • 6

1 Answers1

-1

A possible solution is to put some data into shared preferences and read it in fragment onResume.

Or you could put that informations in other parts, like configuration servers or external service

Obviously if these fragments belong all to the same activity you can put informations into your activity, then you can read it from that attached activity.

For remote fetched data

You may put your data into a singleton class only responsible to keep data. Keep in mind that in android a singleton could be destroyed in some limit cases, so when your fragment come back in foreground check if the singleton is empty and eventually repeat your fetch call

You can see an example here

firegloves
  • 5,581
  • 2
  • 29
  • 50
  • If you do that and onResume you go to listView and do like data: data.clear(); data.addAll(dataFromServer) you loose the state of scroll of listView. – user1245809 Apr 27 '18 at 14:37
  • sure. can you be more precise about what you need? – firegloves Apr 27 '18 at 14:39
  • I mean, you need to change data into a background fragment without loosing scroll state? – firegloves Apr 27 '18 at 14:39
  • I have many fragments in backstack, then I notify about some change that can be realated to all of this fragments, how I make sure that when those fragments are resume, they will have latest state? – user1245809 Apr 29 '18 at 07:44
  • Yeah but if you speak about data retrieven by the server you may use an approach, if you speak about a local preference you may use another approach and so on – firegloves Apr 30 '18 at 08:09