SlideShare a Scribd company logo
1 of 27
Download to read offline
Dalvik Android  Talks
Event Bus
Android  Developer
Gokhan  Arik
Jun  27,  2016
www.gokhanarik.com
Introduction
● What  is  an  Event  Bus?
● Callback  vs  Broadcast  Receiver  vs  Event  Bus
● Event  Bus  Libraries  for  Android
▪ Otto  by  Square  (deprecated   on  January  15,  2016)
▪ EventBus  by  greenrobot
▪ RxJava  by  ReactiveX
● Q/A
● References
What  is  an  Event  Bus?
● System  Bus
● Central  hub
● Flexible  and  modular
What  is  an  Event  Bus?
How  can  I  pass  value  from  X  to  Y  when  click  on  Z?
● Callback  (a.k.a  Listener)
● Broadcast  Receiver
● Event  Bus
What  is  an  Event  Bus?
Common  Crash  in  Android
java.lang.IllegalStateException:  Can  not perform  this  action  after  onSaveInstanceState
at  android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)
at  android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)
at  android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at  android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
What  is  an  Event  Bus?
Callback
/**
*  Interface   definition   for  a  callback   to  be  invoked   when   a  view  is  clicked.
*/
public interface OnClickListener {
/**
*  Called   when   a  view  has  been   clicked.
*
*  @param v  The  view   that  was  clicked.
*/
void onClick(View v);
}
What  is  an  Event  Bus?
Broadcast  Receiver
private MyReceiver mReceiver;
void onResume()   {
IntentFilter filter   = new IntentFilter("com.example.MyEvent");
mReceiver   = new MyReceiver();
registerReceiver(receiver,   filter);
}
void onPause()   {
unregisterReceiver(mReceiver);
}
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context,   Intent intent)   {
Toast.makeText(context,   "MyEvent",   Toast.LENGTH_LONG).show();
}
}
}
What  is  an  Event  Bus?
Broadcast  Receiver
public void sendBroadcast()   {
Intent   intent   = new Intent("com.example.MyEvent");
intent.putExtra("myParam",   "Hello");
sendBroadcast(intent);
}
What  is  an  Event  Bus?
Event  Bus
● Publish  &  Subscribe  Pattern  implementation  (similar  to  Observable)
● Component  to  component  communication  without  direct  reference
● Three  well-­known  libraries  for  Android
▪ Otto  by  Square  (deprecated   on  January  15,  2016)
▪ EventBus  by  greenrobot
▪ RxJava  by  ReactiveX
What  is  an  Event  Bus?
Event  Bus
Callback  vs  Broadcast  Receiver  vs  Event  Bus
Callback
Pros
● Easy  to  implement  for  small  projects
Cons
● Excessive  amount  of  boilerplate  code
● Unnecessary  method  overrides
Callback  vs  Broadcast  Receiver  vs  Event  Bus
Broadcast  Receiver
Pros
● Native  solution  to  problem
▪ Consistency  in  the  code
Cons
● Too  much  code  for  a  simple  task
Callback  vs  Broadcast  Receiver  vs  Event  Bus
Event  Bus
Pros
● Cleaner,  maintainable,  extensible,  flexible  and  more  readable  code
● Easier  to  test
● Multiple  receivers
● Subscribing  to  events  you  need
● No  direct  reference  between  components
Cons
● Hard  to  maintain  list  of  publishers  (fewer  publisher  recommended)  
● No  auto-­complete  support  from  IDE
● Powerful  but  easily  can  be  abused
Otto  by  Square
Event  Bus  Libraries  for  Android
● Fork  of  Guava  based  Event  Bus
● Designed  for  Android
● Deprecated  on  January  15,  2016
Otto  by  Square
Event  Bus  Libraries  for  Android
public class UpdateDataEvent {
public String data;
public UpdateDataEvent(String data)  {
this.data  = data;
}
}
Otto  by  Square
Event  Bus  Libraries  for  Android
//  Use  as  a  singleton
Bus bus  = new Bus();
//  Publish  an  event.  Posting  to  the  bus  is  a  synchronous  action.
bus.post(new UpdateDataEvent("New  Data!"));
//  Subscribe  to  a  specific  event.  Any  method  name.  As  long  as  annotated  with  @Subscribe
@Subscribe
public void dataUpdated(UpdateDataEvent event)  {
//  React  to  the  event  (ex.  update  UI,  save  data  to  database)
Log.v(TAG,  "Data:  " + event.data);
}
Otto  by  Square
Event  Bus  Libraries  for  Android
//  Register  your  class
bus.register(this);  //  inside  onStart()  method
bus.unregister(this);  //  inside  onStop()  method
//  Produce
@Produce
public UpdateDataEvent produceDataUpdate()  {
//  Assuming  data  exists.
return new AnswerAvailableEvent(this.data);
}
EventBus  by  greenrobot
Event  Bus  Libraries  for  Android
● Developers  of  greenDAO
● Same  basic  semantics  as  Otto
● Faster  than  Otto
● Richer  feature  set  
EventBus  by  greenrobot
Event  Bus  Libraries  for  Android
public class UpdateDataEvent {
public String data;
public UpdateDataEvent(String data)  {
this.data  = data;
}
}
EventBus  by  greenrobot
Event  Bus  Libraries  for  Android
//  Similar  to  Otto
EventBus bus  = EventBus.getDefault();
//  With  richer  feature  set
EventBus bus  = EventBus.builder().logNoSubscriberMessages(false).sendNoSubscriberEvent(false).build();
EventBus bus  = EventBus.builder().throwSubscriberException(true).build();
//  Must  be  called  once.  FOr  example,  in  Application  class’  onCreate()  method
EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).installDefaultEventBus();
//  Publish  an  event
bus.post(new UpdateDataEvent("New  data!"));
EventBus  by  greenrobot
Event  Bus  Libraries  for  Android
//  Register  your  class
bus.register(this);  //  inside  onStart()  method
bus.unregister(this);  //  inside  onStop()  method
//  Subscribe  to  a  specific  event.  Any  method  name.  As  long  as  annotated  with  @Subscribe
@Subscribe
public void dataUpdated(UpdateDataEvent event)  {
//  React  to  the  event  (ex.  update  UI,  save  data  to  database)
Log.v(TAG,  "Data:  " + event.data);
}
EventBus  by  greenrobot
Event  Bus  Libraries  for  Android
@Subscribe(threadMode  = ThreadMode.POSTING)  //  Opt.
public void onMessage(MessageEvent event)  {
log(event.message);
}
ThreadMode
● POSTING
▪ Default  ThreadMode
▪ Good  for  simple  tasks
● MAIN
▪ Runs  on  main/UI  thread
● BACKGROUND
● ASYNC @Subscribe(threadMode  = ThreadMode.BACKGROUND)
public void onMessage(MessageEvent event){
saveToDisk(event.message);
}
@Subscribe(threadMode  = ThreadMode.MAIN)
public void onMessage(MessageEvent event)  {
textField.setText(event.message);
}
EventBus  by  greenrobot
Event  Bus  Libraries  for  Android
//  Posting   a  Sticky   Event
bus.postSticky(new LastLocationEvent("Omaha!"));
Sticky  Events
● Last  sticky  event  kept  in  memory
● Delivered  to  subscriber  as  soon  as  
registered
@Override
public void onStart()   {
super.onStart();
bus.register(this);
}
@Subscribe(sticky   = true,   threadMode   = ThreadMode.MAIN)
public void onEvent(LastLocationEvent event)   {
textField.setText(event.message);
}
@Override
public void onStop()   {
bus.unregister(this);
super.onStop();
}
RxJava  by  ReactiveX
Event  Bus  Libraries  for  Android
//  this  is  the  middleman  object
public class RxBus {
private Subject<Object,  Object> bus  = new
SerializedSubject<>(PublishSubject.create());
public void send(Object o)  {
bus.onNext(o);
}
public Observable<Object> toObserverable()  {
return bus;
}
}
@OnClick(R.id.btn_demo_rxbus_tap)
public void onTapButtonClicked()   {
bus.send(new TapEvent());
}
bus.toObserverable()
.subscribe(new Action1<Object>()   {
@Override
public void call(Object event)   {
if(event   instanceof TapEvent)   {
_showTapText();
}else if(event   instanceof SomeOtherEvent)   {
_doSomethingElse();
}
}
});
Dalvik  Android  Talks
Q/A
Dalvik  Android  Talks
Thank  You
References
1. https://github.com/square/otto-­intellij-­plugin
2. http://cases.azoft.com/message-­bus-­in-­android-­apps/
3. http://poohdish.ghost.io/what-­is-­event-­bus/
4. http://timnew.me/blog/2014/12/06/typical-­eventbus-­design-­patterns/
5. https://github.com/greenrobot/EventBus/blob/master/COMPARISON.md
6. http://nerds.weddingpartyapp.com/tech/2014/12/24/implementing-­an-­event-­bus-­with-­rxjava-­rxbus/
7. https://github.com/greenrobot/EventBus
8. https://github.com/kaushikgopal/RxJava-­Android-­
Samples/blob/master/app/src/main/java/com/morihacky/android/rxjava/rxbus

More Related Content

Similar to Event Bus by Gokhan Arik - Dalvik Android Talks at CRi

Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web ToolkitsYiguang Hu
 
Javascript as a target language - GWT KickOff - Part 2/2
Javascript as a target language - GWT KickOff - Part 2/2Javascript as a target language - GWT KickOff - Part 2/2
Javascript as a target language - GWT KickOff - Part 2/2JooinK
 
Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Mahmoud Hamed Mahmoud
 
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitJava Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitIMC Institute
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Androidgreenrobot
 
Web polyglot programming
Web polyglot programmingWeb polyglot programming
Web polyglot programmingDmitry Buzdin
 
Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTudor Barbu
 
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...Matt Spradley
 
AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesRainer Stropek
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web developmentalice yang
 
An approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAn approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAndrei Sebastian Cîmpean
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
Hybrid application development
Hybrid application developmentHybrid application development
Hybrid application developmentEngin Hatay
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Enginecatherinewall
 
Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...
Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...
Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...COMAQA.BY
 
Writing java script for Csharp's Blazor
Writing java script for Csharp's BlazorWriting java script for Csharp's Blazor
Writing java script for Csharp's BlazorEd Charbeneau
 
Easing offline web application development with GWT
Easing offline web application development with GWTEasing offline web application development with GWT
Easing offline web application development with GWTArnaud Tournier
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web ToolkitsYiguang Hu
 

Similar to Event Bus by Gokhan Arik - Dalvik Android Talks at CRi (20)

Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 
Javascript as a target language - GWT KickOff - Part 2/2
Javascript as a target language - GWT KickOff - Part 2/2Javascript as a target language - GWT KickOff - Part 2/2
Javascript as a target language - GWT KickOff - Part 2/2
 
Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development
 
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitJava Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Android
 
Web polyglot programming
Web polyglot programmingWeb polyglot programming
Web polyglot programming
 
Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabs
 
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
 
AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile Services
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web development
 
An approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAn approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSockets
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Hybrid application development
Hybrid application developmentHybrid application development
Hybrid application development
 
GWT
GWTGWT
GWT
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Engine
 
Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...
Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...
Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...
 
Writing java script for Csharp's Blazor
Writing java script for Csharp's BlazorWriting java script for Csharp's Blazor
Writing java script for Csharp's Blazor
 
Easing offline web application development with GWT
Easing offline web application development with GWTEasing offline web application development with GWT
Easing offline web application development with GWT
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 

Recently uploaded

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 

Recently uploaded (20)

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 

Event Bus by Gokhan Arik - Dalvik Android Talks at CRi

  • 1. Dalvik Android  Talks Event Bus Android  Developer Gokhan  Arik Jun  27,  2016 www.gokhanarik.com
  • 2. Introduction ● What  is  an  Event  Bus? ● Callback  vs  Broadcast  Receiver  vs  Event  Bus ● Event  Bus  Libraries  for  Android ▪ Otto  by  Square  (deprecated   on  January  15,  2016) ▪ EventBus  by  greenrobot ▪ RxJava  by  ReactiveX ● Q/A ● References
  • 3. What  is  an  Event  Bus? ● System  Bus ● Central  hub ● Flexible  and  modular
  • 4. What  is  an  Event  Bus? How  can  I  pass  value  from  X  to  Y  when  click  on  Z? ● Callback  (a.k.a  Listener) ● Broadcast  Receiver ● Event  Bus
  • 5. What  is  an  Event  Bus? Common  Crash  in  Android java.lang.IllegalStateException:  Can  not perform  this  action  after  onSaveInstanceState at  android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341) at  android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352) at  android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595) at  android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
  • 6. What  is  an  Event  Bus? Callback /** *  Interface   definition   for  a  callback   to  be  invoked   when   a  view  is  clicked. */ public interface OnClickListener { /** *  Called   when   a  view  has  been   clicked. * *  @param v  The  view   that  was  clicked. */ void onClick(View v); }
  • 7. What  is  an  Event  Bus? Broadcast  Receiver private MyReceiver mReceiver; void onResume()   { IntentFilter filter   = new IntentFilter("com.example.MyEvent"); mReceiver   = new MyReceiver(); registerReceiver(receiver,   filter); } void onPause()   { unregisterReceiver(mReceiver); } public class MyReceiver extends BroadcastReceiver { public void onReceive(Context context,   Intent intent)   { Toast.makeText(context,   "MyEvent",   Toast.LENGTH_LONG).show(); } } }
  • 8. What  is  an  Event  Bus? Broadcast  Receiver public void sendBroadcast()   { Intent   intent   = new Intent("com.example.MyEvent"); intent.putExtra("myParam",   "Hello"); sendBroadcast(intent); }
  • 9. What  is  an  Event  Bus? Event  Bus ● Publish  &  Subscribe  Pattern  implementation  (similar  to  Observable) ● Component  to  component  communication  without  direct  reference ● Three  well-­known  libraries  for  Android ▪ Otto  by  Square  (deprecated   on  January  15,  2016) ▪ EventBus  by  greenrobot ▪ RxJava  by  ReactiveX
  • 10. What  is  an  Event  Bus? Event  Bus
  • 11. Callback  vs  Broadcast  Receiver  vs  Event  Bus Callback Pros ● Easy  to  implement  for  small  projects Cons ● Excessive  amount  of  boilerplate  code ● Unnecessary  method  overrides
  • 12. Callback  vs  Broadcast  Receiver  vs  Event  Bus Broadcast  Receiver Pros ● Native  solution  to  problem ▪ Consistency  in  the  code Cons ● Too  much  code  for  a  simple  task
  • 13. Callback  vs  Broadcast  Receiver  vs  Event  Bus Event  Bus Pros ● Cleaner,  maintainable,  extensible,  flexible  and  more  readable  code ● Easier  to  test ● Multiple  receivers ● Subscribing  to  events  you  need ● No  direct  reference  between  components Cons ● Hard  to  maintain  list  of  publishers  (fewer  publisher  recommended)   ● No  auto-­complete  support  from  IDE ● Powerful  but  easily  can  be  abused
  • 14. Otto  by  Square Event  Bus  Libraries  for  Android ● Fork  of  Guava  based  Event  Bus ● Designed  for  Android ● Deprecated  on  January  15,  2016
  • 15. Otto  by  Square Event  Bus  Libraries  for  Android public class UpdateDataEvent { public String data; public UpdateDataEvent(String data)  { this.data  = data; } }
  • 16. Otto  by  Square Event  Bus  Libraries  for  Android //  Use  as  a  singleton Bus bus  = new Bus(); //  Publish  an  event.  Posting  to  the  bus  is  a  synchronous  action. bus.post(new UpdateDataEvent("New  Data!")); //  Subscribe  to  a  specific  event.  Any  method  name.  As  long  as  annotated  with  @Subscribe @Subscribe public void dataUpdated(UpdateDataEvent event)  { //  React  to  the  event  (ex.  update  UI,  save  data  to  database) Log.v(TAG,  "Data:  " + event.data); }
  • 17. Otto  by  Square Event  Bus  Libraries  for  Android //  Register  your  class bus.register(this);  //  inside  onStart()  method bus.unregister(this);  //  inside  onStop()  method //  Produce @Produce public UpdateDataEvent produceDataUpdate()  { //  Assuming  data  exists. return new AnswerAvailableEvent(this.data); }
  • 18. EventBus  by  greenrobot Event  Bus  Libraries  for  Android ● Developers  of  greenDAO ● Same  basic  semantics  as  Otto ● Faster  than  Otto ● Richer  feature  set  
  • 19. EventBus  by  greenrobot Event  Bus  Libraries  for  Android public class UpdateDataEvent { public String data; public UpdateDataEvent(String data)  { this.data  = data; } }
  • 20. EventBus  by  greenrobot Event  Bus  Libraries  for  Android //  Similar  to  Otto EventBus bus  = EventBus.getDefault(); //  With  richer  feature  set EventBus bus  = EventBus.builder().logNoSubscriberMessages(false).sendNoSubscriberEvent(false).build(); EventBus bus  = EventBus.builder().throwSubscriberException(true).build(); //  Must  be  called  once.  FOr  example,  in  Application  class’  onCreate()  method EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).installDefaultEventBus(); //  Publish  an  event bus.post(new UpdateDataEvent("New  data!"));
  • 21. EventBus  by  greenrobot Event  Bus  Libraries  for  Android //  Register  your  class bus.register(this);  //  inside  onStart()  method bus.unregister(this);  //  inside  onStop()  method //  Subscribe  to  a  specific  event.  Any  method  name.  As  long  as  annotated  with  @Subscribe @Subscribe public void dataUpdated(UpdateDataEvent event)  { //  React  to  the  event  (ex.  update  UI,  save  data  to  database) Log.v(TAG,  "Data:  " + event.data); }
  • 22. EventBus  by  greenrobot Event  Bus  Libraries  for  Android @Subscribe(threadMode  = ThreadMode.POSTING)  //  Opt. public void onMessage(MessageEvent event)  { log(event.message); } ThreadMode ● POSTING ▪ Default  ThreadMode ▪ Good  for  simple  tasks ● MAIN ▪ Runs  on  main/UI  thread ● BACKGROUND ● ASYNC @Subscribe(threadMode  = ThreadMode.BACKGROUND) public void onMessage(MessageEvent event){ saveToDisk(event.message); } @Subscribe(threadMode  = ThreadMode.MAIN) public void onMessage(MessageEvent event)  { textField.setText(event.message); }
  • 23. EventBus  by  greenrobot Event  Bus  Libraries  for  Android //  Posting   a  Sticky   Event bus.postSticky(new LastLocationEvent("Omaha!")); Sticky  Events ● Last  sticky  event  kept  in  memory ● Delivered  to  subscriber  as  soon  as   registered @Override public void onStart()   { super.onStart(); bus.register(this); } @Subscribe(sticky   = true,   threadMode   = ThreadMode.MAIN) public void onEvent(LastLocationEvent event)   { textField.setText(event.message); } @Override public void onStop()   { bus.unregister(this); super.onStop(); }
  • 24. RxJava  by  ReactiveX Event  Bus  Libraries  for  Android //  this  is  the  middleman  object public class RxBus { private Subject<Object,  Object> bus  = new SerializedSubject<>(PublishSubject.create()); public void send(Object o)  { bus.onNext(o); } public Observable<Object> toObserverable()  { return bus; } } @OnClick(R.id.btn_demo_rxbus_tap) public void onTapButtonClicked()   { bus.send(new TapEvent()); } bus.toObserverable() .subscribe(new Action1<Object>()   { @Override public void call(Object event)   { if(event   instanceof TapEvent)   { _showTapText(); }else if(event   instanceof SomeOtherEvent)   { _doSomethingElse(); } } });
  • 27. References 1. https://github.com/square/otto-­intellij-­plugin 2. http://cases.azoft.com/message-­bus-­in-­android-­apps/ 3. http://poohdish.ghost.io/what-­is-­event-­bus/ 4. http://timnew.me/blog/2014/12/06/typical-­eventbus-­design-­patterns/ 5. https://github.com/greenrobot/EventBus/blob/master/COMPARISON.md 6. http://nerds.weddingpartyapp.com/tech/2014/12/24/implementing-­an-­event-­bus-­with-­rxjava-­rxbus/ 7. https://github.com/greenrobot/EventBus 8. https://github.com/kaushikgopal/RxJava-­Android-­ Samples/blob/master/app/src/main/java/com/morihacky/android/rxjava/rxbus