+Strahinja Ajvaz Thanks! It's one of my favorite design patterns to use in my apps. Let me know if there's something in particular that you'd rather not spend months learning and I'll try to help you out! Thanks for the awesome comment!
+Mark O'Sullivan Thanks! Glad you enjoyed it. I plan on doing a few other tutorials on awesome Android libraries that have saved me hours of dev time. Stay tuned!
Best comment ever! Thanks for that! I just started the channel in January. I teach some of this stuff at a large university, so I think that helps. I also run my own mobile dev company, so I haven't had too much time to dedicate to promoting the channel. Feel free to share this video amongst your friends and get them to subscribe. I'll be extremely grateful. Thanks again!
Sure I will! Just don't stop and please focus on these advanced topics as there are tons of tutorials already available for basic stuff. I'm freelance dev myself and I struggle when learning new pattern or technology due to lack of proper learning material.
At 4:21 you stated "it has to be called onEvent". CORRECTION: Version 3.x: Event handling methods must be annotated by @Subscribe, must be public, return nothing (void), and have exactly one parameter (the event). In Version 2.x it was as follows: By convention, event handling methods must be named "onEvent", be public, return nothing (void), and have exactly one parameter (the event).
Yep! Thanks for pointing that out. The newer version has slightly different requirements. I'll be revisiting this video and likely recreating it with the new info.
Hi, Thanks for the nice tutorial. Can you please tell me where can we get the list of all the @Subscribe methods and their usage. Also what is the difference if data is send and subscribed by say FragmentsA and B, which do not exist at the same time.
Good catch. Not sure what it was for but I doubt it was the fault of Event Bus as it's pretty optimized. Might have just been the computer I was using, being slow.
I am using a bottombar with three fragments associated with it. The first fragment uses a recycler view . My question is how to pass values which I receive from the recycler adapter to the third fragment using eventBus?
That data should live in a third class, preferably a singleton, where you can gain access to it from any class. You can keep a copy in the View's adapter, but it shouldn't be the main repo. The third fragment then can access the data in that singleton at any time, especially when it gets notified that there's new data to get.
+László K Szia Laci. Thanks for the question! Too many callbacks is one. But with EventBus objects don't need to know about each other. They can also send messages to multiple objects at once. You can accomplish the same things with callbacks but it messy and hard to maintain. It's one main reason for "spaghetti" code. Hopefully that cleared it up some. Let me know if you still have questions!
Thanks, what about when we have more activities, that listening to the same things... Am I have to unregister in the activity that stopped and start again when started? How can we handle this?
That's exactly what you have to do. Take a look at the getting started to see how to register and unregister event listening in the onStart and onStop methods: greenrobot.org/eventbus/documentation/how-to-get-started/
Never used RxBus but from the quick look at it, it doesn't look as great as the other two. I began using Otto first, but switched to Green Robot's Event Bus since Otto doesn't notify you in the main thread. Here's a comparison chart github.com/greenrobot/EventBus/blob/master/COMPARISON.md I mostly use EventBus for updating and keeping the UI thread synced, so getting notified on the Main thread is important to me. That chart might be biased though.
Sorry for the late reply. I'm not sure why you would want to replace onActivityResult, but you can always post an EventBus event in the onActivityResult callback. If you really don't want to do that, I suggest creating a custom camera activity instead of using the system's built in camera activity. This gives you a lot more flexibility but requires more coding. Let me know if that answers your question. Thanks!
Easy Peasy! Awesome tuts. Though I bumped in to this problem, where my receiving Fragment has a method postMethod() and what it does is saving users post, The problem is the sender Fragment is a map, where I am getting the latitude of the location so this fragment initially fires the value of latitude and the receiving Fragment receives the value initially, but knowing the postMethod is the one responsible for saving users post the value can't be receive because the sender Fragment is already dismiss, Any thoughts or solutions for this? Thanks in advance :D
Great question. Thanks! I have a simple answer, but it'll require a bit more work on your side. Instead of getting the GPS coordinates from the map fragment, you'll have to request them from the LocationManager using Android's location services. I have a video on that but I think it's in one of the Android live streams I did. Here's some documentation on it in the mean time: developer.android.com/guide/topics/location/index.html The reason you'll want the service and the location manager is, you'll want to store that information in a class that lives throughout the application lifecycle, namely a singleton that gets instantiated at application launch. I should have a video coming out soon that will handle all of this, including the use of EventBus. So stay tuned! Thanks for the comment!
Wow! Didn't expect for the fast reply, anyways thank you so much! You've earned my sub and definitely going to stay tune to your upcoming vid. tuts. More power to your channel @Electronic Armory!
Tutorial good. But i was trying figuring out how to handle with EventBus when your Activity dead and you have to send Notification to users if Activity dead. But when your Activity alive you don't have to send Notification. and i tried to do all this things through EventBus but i didn't do this. so difficult
Store all of that information in a separate object. Then when your activity loads up, check that separate object that is storing that data. Don't store any data you need to share in an activity. Thanks for the question!
In the onEvent callback, simply create a new intent and launch it as usual. You'd have to be careful with this as you'd have to make sure where it's getting called is going to still be around to call the code.
Yes. Simply change the event type that is a parameter for that function to overload the method and have multiple onEvent methods for different event types.
Sure. You would just register each view with EventBus as it was instantiated. Then each one of them would get a notification, assuming they're all the same subclass and implemented the same way. Then, don't forgot to unregister them as they get destroyed, but that's the basics of it. Were you looking to do anything specifically with it?
Yes.I have 3 fragments in an Activity: FragmentA, FragmentB and FragmentC (all different subclasses). FragmentA has 1 EditText and FragmentB has a Button. I am trying to send EditText data from FragmentA to FragmentB which would be displayed as a Toast when the Button is clicked in FragmentB. I am not very familiar with how fragments work, I'm a noob at Android :P
That scenario would have been a better example to make a video on. Perhaps I'll find time to do that since it's a great illustration of EventBus. FragmentA registers to receive a notification. Let's call that ButtonPressNotification. In FragmentB, when that button is pressed, in your Click Handler, post that ButtonPressNotification notification to EventBus. When FragmentA receives that notification in its notification handler, simply create a toast from FragmentA. If FragmentC needs to know too, either register the same notification, or, create a second notification class, say ButtonPressedAndProcessedNotification (or something better), and post that from FragmentA, after the toast. Finally, if you need to have this handled on multiple views, in a pager, post the notification, but attach the index of the slide with the notification. That way, when the other views/fragments get that notification, they can check to see if that notification is for their view. If not, they can ignore it. If so, they can handle it like normal. That way you can keep it dynamic. Hope I made that clear! Let me know if you need me to elaborate on anything. Thanks!
+Massive Developer The performance is great and better than doing it manually by keeping your own references to subscribers. Just make sure you unsubscribe when the instance no longer needs to know about the event, per the documentation. Great question! Thanks!
Make sure you uncheck Offline work in Preferences or File -> Settings -> Build, Execution, Deployment -> Gradle -> Offline Work Once unchecked, restart Android Studio and make sure you resync Gradle. Also, make sure you copied and paste the Gradle dependency line from GreenRobot's documentation since it could have been updated.
Not seeing any issues. Sounds like some kind of strange network error. Try cleaning the project, hitting that host directly or seeing if the proxy settings are correct, or turned off.
This example has a memory leak becouse you did not unsubscribe it in on destroy. What is more an activity will not be notified about new event if it will be destroyed by the system while ChildActivity is launched.
Thanks for pointing that out. I forgot to unsubscribe to the event in the onStop, or similar life cycle method. I'll add an annotation to the video. It's not a memory leak however since no memory is being allocated when you register the class. Event Bus keeps an internal array of all the objects and their registered notifications. If one of the objects in the array has no reference, since it was deallocated, Event Bus moves on. You're also right about the parent activity not being notified if it gets destroyed when the child appears. That's something that's rare, but can certainly happen (all the time if you enable that feature in the simulator). However, the observer pattern should not be relied on to relay mission critical data but instead should only be used for syncing or reacting to real time events as they happen. If you have a background activity, when it resumes or is recreated, it should check a static object, say a singleton, to see if any data updated in it's absence. I'm working on putting together a video that illustrates that even better so make sure you stay tuned and keep providing the critical feedback to me. I appreciate it!!! Thanks!
Good question. EventBus keeps a list of observers that it'll send that event to. If that observer doesn't exist, it gets ignored. However, if you have a long list of observers that don't exist, it could slow down performance. So unregister the observer in the onPause or onStop.
You can unregister the Activity when that Activity is destroyed in the onDestroy so that the subscriber will always receive the notification. EventBus allows you to get those notifications on different threads, so if the activity is not running, you can get it in a background thread, store the value in a member variable and then when in your onResume function, use that member variable to perform the work on the main thread so you can update the UI. But if you want to make absolutely sure the data is processed, you'll want to make a direct call to a controller or manager that controls that data. For example, if EventBus is telling me I there's a new piece of data, or even if it doesn't, on my Activity's onResume, I can go to the controller that holds that data and see if there's anything new there, or request data that's new within the last few minutes, or whatever your logic needs to look like. While EventBus should work to ensure you get the notifications, if you're using it to send hundreds, there's a possibility the notification doesn't get sent, or is delayed so it's always a good idea to ensure you have the latest data from a central data authority.
Yes. Great comment. EventBus is easier to use than the built in broadcast receivers. Green Robot actually addresses this on their site in the FAQ: Q: How's EventBus different to Android's BroadcastReceiver/Intent system? A: Unlike Android's BroadcastReceiver/Intent system, EventBus uses standard Java classes as events and offers a more convenient API. EventBus is intended for a lot more use cases where you wouldn't want to go through the hassle of setting up Intents, preparing Intent extras, implementing broadcast receivers, and extracting Intent extras again. Also, EventBus comes with a much lower overhead.
Me too. I started using it since the syntax as so simple, straight forward and easy to understand. It's also extremely flexible with the built in annotations.
Bro I was having nightmares until I saw this video, Thanks a lot !
AWESOME TUTORIAL LIKE REALLLLLY AWESOME i spent months trying to understand this pattern and no one could explain it. YOU SIR ARE AWESOME!
+Strahinja Ajvaz Thanks! It's one of my favorite design patterns to use in my apps. Let me know if there's something in particular that you'd rather not spend months learning and I'll try to help you out! Thanks for the awesome comment!
+Strahinja Ajvaz You got it. I'll add it to the list of videos to do. Thanks!
Perfect tutorial on Event Bus.... Glad I found it
Thanks! I'm happy it helped you out.
Great explanation and demonstration of EventBus. Going to try it out now!
+Mark O'Sullivan Thanks! Glad you enjoyed it. I plan on doing a few other tutorials on awesome Android libraries that have saved me hours of dev time. Stay tuned!
Why this channel have so few subscribers? That was a brilliant explanation!
Best comment ever! Thanks for that! I just started the channel in January. I teach some of this stuff at a large university, so I think that helps. I also run my own mobile dev company, so I haven't had too much time to dedicate to promoting the channel. Feel free to share this video amongst your friends and get them to subscribe. I'll be extremely grateful. Thanks again!
Sure I will! Just don't stop and please focus on these advanced topics as there are tons of tutorials already available for basic stuff. I'm freelance dev myself and I struggle when learning new pattern or technology due to lack of proper learning material.
Will do, thanks! I plan on putting together another quick Android video that I'm sure you'll find interesting.
Great explanation thank you for tutorials
Thanks for the comment! Great to hear they helped you out.
This was an amazing tutorial, thanks!
Best tutorial on Event bus!!!
Thanks for letting me know. My next video will be an update to EventBus using Kotlin, so I'm glad to hear you liked this one.
sir what if we want it for 2 bus ? then how to do this
Amazing lecture found ever...
Thanks! I'm currently updating this video for Kotlin, if you're interested in learning Kotlin on Android. Thanks for the comment!
best video on eventbus, thanks man
Awesome! Very happy you think so. I love EventBus. I use it in all my Android apps. Thanks!
This tutorial is lovely
Awesome! Thanks!
Great video! Tnx
You're welcome! I have a Kotlin version of this video too if needed. Thanks!
At 4:21 you stated "it has to be called onEvent". CORRECTION: Version 3.x: Event handling methods must be annotated by @Subscribe, must be public, return nothing (void), and have exactly one parameter (the event). In Version 2.x it was as follows: By convention, event handling methods must be named "onEvent", be public, return nothing (void), and have exactly one parameter (the event).
Yep! Thanks for pointing that out. The newer version has slightly different requirements. I'll be revisiting this video and likely recreating it with the new info.
Hi, Thanks for the nice tutorial.
Can you please tell me where can we get the list of all the @Subscribe methods and their usage.
Also what is the difference if data is send and subscribed by say FragmentsA and B, which do not exist at the same time.
Great tutorial. I noticed the message "The application may be doing too much work" in your logs. Is this an eventbus message and is it important?
Good catch. Not sure what it was for but I doubt it was the fault of Event Bus as it's pretty optimized. Might have just been the computer I was using, being slow.
I am using a bottombar with three fragments associated with it. The first fragment uses a recycler view . My question is how to pass values which I receive from the recycler adapter to the third fragment using eventBus?
That data should live in a third class, preferably a singleton, where you can gain access to it from any class. You can keep a copy in the View's adapter, but it shouldn't be the main repo. The third fragment then can access the data in that singleton at any time, especially when it gets notified that there's new data to get.
Awesome tutorial !
Thanks for the comment!
nice explanation . thanks for making this video :)
Glad you liked it! Thanks for watching!
Why Eventbus better than a normal interface callback? I think this is the same..
Callback hell?
+László K Szia Laci. Thanks for the question! Too many callbacks is one. But with EventBus objects don't need to know about each other. They can also send messages to multiple objects at once. You can accomplish the same things with callbacks but it messy and hard to maintain. It's one main reason for "spaghetti" code. Hopefully that cleared it up some. Let me know if you still have questions!
Thanks, what about when we have more activities, that listening to the same things... Am I have to unregister in the activity that stopped and start again when started?
How can we handle this?
That's exactly what you have to do. Take a look at the getting started to see how to register and unregister event listening in the onStart and onStop methods: greenrobot.org/eventbus/documentation/how-to-get-started/
OK, it is very simple. What is better? Otto, greenrobot, or RxBus?
Never used RxBus but from the quick look at it, it doesn't look as great as the other two. I began using Otto first, but switched to Green Robot's Event Bus since Otto doesn't notify you in the main thread. Here's a comparison chart github.com/greenrobot/EventBus/blob/master/COMPARISON.md
I mostly use EventBus for updating and keeping the UI thread synced, so getting notified on the Main thread is important to me. That chart might be biased though.
Thank you.Can you show how can i use eventbus replacing onactivityResult while using camera etc
Sorry for the late reply. I'm not sure why you would want to replace onActivityResult, but you can always post an EventBus event in the onActivityResult callback. If you really don't want to do that, I suggest creating a custom camera activity instead of using the system's built in camera activity. This gives you a lot more flexibility but requires more coding. Let me know if that answers your question. Thanks!
nice explanation thanks
Thanks for the comment!
Easy Peasy! Awesome tuts.
Though I bumped in to this problem, where my receiving Fragment has a method postMethod() and what it does is saving users post, The problem is the sender Fragment is a map, where I am getting the latitude of the location so this fragment initially fires the value of latitude and the receiving Fragment receives the value initially, but knowing the postMethod is the one responsible for saving users post the value can't be receive because the sender Fragment is already dismiss, Any thoughts or solutions for this? Thanks in advance :D
Great question. Thanks! I have a simple answer, but it'll require a bit more work on your side. Instead of getting the GPS coordinates from the map fragment, you'll have to request them from the LocationManager using Android's location services. I have a video on that but I think it's in one of the Android live streams I did. Here's some documentation on it in the mean time: developer.android.com/guide/topics/location/index.html
The reason you'll want the service and the location manager is, you'll want to store that information in a class that lives throughout the application lifecycle, namely a singleton that gets instantiated at application launch. I should have a video coming out soon that will handle all of this, including the use of EventBus. So stay tuned! Thanks for the comment!
Wow! Didn't expect for the fast reply, anyways thank you so much! You've earned my sub and definitely going to stay tune to your upcoming vid. tuts. More power to your channel @Electronic Armory!
Tutorial good. But i was trying figuring out how to handle with EventBus when your Activity dead and you have to send Notification to users if Activity dead. But when your Activity alive you don't have to send Notification. and i tried to do all this things through EventBus but i didn't do this. so difficult
Store all of that information in a separate object. Then when your activity loads up, check that separate object that is storing that data. Don't store any data you need to share in an activity. Thanks for the question!
great
THANK YOUUU!
hello please kindly tell me how to call another activity (child activity ) by using greenrobot in android
In the onEvent callback, simply create a new intent and launch it as usual. You'd have to be careful with this as you'd have to make sure where it's getting called is going to still be around to call the code.
it is possible to make onEvent() two times in the same class ??
Yes. Simply change the event type that is a parameter for that function to overload the method and have multiple onEvent methods for different event types.
Amazing tutorial. Thank you very much!
Glad you liked it! I have a bunch more Android videos planned, just like this one. Stay tuned!
Can't wait for more content :)
Could you please make a tutorial on how to use EventBus on fragments in Swipe views(View Pager)?
Sure. You would just register each view with EventBus as it was instantiated. Then each one of them would get a notification, assuming they're all the same subclass and implemented the same way. Then, don't forgot to unregister them as they get destroyed, but that's the basics of it. Were you looking to do anything specifically with it?
Yes.I have 3 fragments in an Activity: FragmentA, FragmentB and FragmentC (all different subclasses). FragmentA has 1 EditText and FragmentB has a Button. I am trying to send EditText data from FragmentA to FragmentB which would be displayed as a Toast when the Button is clicked in FragmentB. I am not very familiar with how fragments work, I'm a noob at Android :P
That scenario would have been a better example to make a video on. Perhaps I'll find time to do that since it's a great illustration of EventBus.
FragmentA registers to receive a notification. Let's call that ButtonPressNotification. In FragmentB, when that button is pressed, in your Click Handler, post that ButtonPressNotification notification to EventBus. When FragmentA receives that notification in its notification handler, simply create a toast from FragmentA. If FragmentC needs to know too, either register the same notification, or, create a second notification class, say ButtonPressedAndProcessedNotification (or something better), and post that from FragmentA, after the toast.
Finally, if you need to have this handled on multiple views, in a pager, post the notification, but attach the index of the slide with the notification. That way, when the other views/fragments get that notification, they can check to see if that notification is for their view. If not, they can ignore it. If so, they can handle it like normal. That way you can keep it dynamic.
Hope I made that clear! Let me know if you need me to elaborate on anything. Thanks!
what about performance , dose event bus cost or not ?
+Massive Developer The performance is great and better than doing it manually by keeping your own references to subscribers. Just make sure you unsubscribe when the instance no longer needs to know about the event, per the documentation. Great question! Thanks!
there is an error:could not download eventbus.jar(org.greenrobot:eventbus:3.0.0): No cached version available for offline mode
Make sure you uncheck Offline work in Preferences or File -> Settings -> Build, Execution, Deployment -> Gradle -> Offline Work
Once unchecked, restart Android Studio and make sure you resync Gradle. Also, make sure you copied and paste the Gradle dependency line from GreenRobot's documentation since it could have been updated.
Electronic Armory again it is asking to switch it on stating unknown host 'jcenter.bintray.com'.you may need to adjust the proxy setting in gradle
Not seeing any issues. Sounds like some kind of strange network error. Try cleaning the project, hitting that host directly or seeing if the proxy settings are correct, or turned off.
Thanks!
You're welcome! Hope it was helpful.
Thnx buddy .. 👍🏻
Glad you enjoyed it! I have a Kotlin version of this one coming up soon.
This example has a memory leak becouse you did not unsubscribe it in on destroy. What is more an activity will not be notified about new event if it will be destroyed by the system while ChildActivity is launched.
Thanks for pointing that out. I forgot to unsubscribe to the event in the onStop, or similar life cycle method. I'll add an annotation to the video.
It's not a memory leak however since no memory is being allocated when you register the class. Event Bus keeps an internal array of all the objects and their registered notifications. If one of the objects in the array has no reference, since it was deallocated, Event Bus moves on.
You're also right about the parent activity not being notified if it gets destroyed when the child appears. That's something that's rare, but can certainly happen (all the time if you enable that feature in the simulator). However, the observer pattern should not be relied on to relay mission critical data but instead should only be used for syncing or reacting to real time events as they happen. If you have a background activity, when it resumes or is recreated, it should check a static object, say a singleton, to see if any data updated in it's absence. I'm working on putting together a video that illustrates that even better so make sure you stay tuned and keep providing the critical feedback to me. I appreciate it!!! Thanks!
What happens if the observer is killed when event is sent.
Good question. EventBus keeps a list of observers that it'll send that event to. If that observer doesn't exist, it gets ignored. However, if you have a long list of observers that don't exist, it could slow down performance. So unregister the observer in the onPause or onStop.
@@ElectronicArmory But what if Notification is important and cannot be ignored. Is that Notification received when Activity again comes back to life.
You can unregister the Activity when that Activity is destroyed in the onDestroy so that the subscriber will always receive the notification. EventBus allows you to get those notifications on different threads, so if the activity is not running, you can get it in a background thread, store the value in a member variable and then when in your onResume function, use that member variable to perform the work on the main thread so you can update the UI. But if you want to make absolutely sure the data is processed, you'll want to make a direct call to a controller or manager that controls that data. For example, if EventBus is telling me I there's a new piece of data, or even if it doesn't, on my Activity's onResume, I can go to the controller that holds that data and see if there's anything new there, or request data that's new within the last few minutes, or whatever your logic needs to look like. While EventBus should work to ensure you get the notifications, if you're using it to send hundreds, there's a possibility the notification doesn't get sent, or is delayed so it's always a good idea to ensure you have the latest data from a central data authority.
@@ElectronicArmory Thanks a bunch ! :-)
very good. could you post your presentation?
Absolutely! I posted a link at the bottom of the page: www.electronicarmory.com/articles/eventbus-android-tutorial-observer-pattern
Thanks
I think EventBus is more like Broadcast receivers than Interface...
Yes. Great comment. EventBus is easier to use than the built in broadcast receivers. Green Robot actually addresses this on their site in the FAQ:
Q: How's EventBus different to Android's BroadcastReceiver/Intent system?
A: Unlike Android's BroadcastReceiver/Intent system, EventBus uses standard Java classes as events and offers a more convenient API. EventBus is intended for a lot more use cases where you wouldn't want to go through the hassle of setting up Intents, preparing Intent extras, implementing broadcast receivers, and extracting Intent extras again. Also, EventBus comes with a much lower overhead.
Thanks
You're welcome!
i prefer this than react, it doesn't introduce new syntax
Me too. I started using it since the syntax as so simple, straight forward and easy to understand. It's also extremely flexible with the built in annotations.