Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Dagger2 Optional bindings

funnelbit
November 28, 2016

Dagger2 Optional bindings

funnelbit

November 28, 2016
Tweet

More Decks by funnelbit

Other Decks in Technology

Transcript

  1. &OUSZ public class Entry {
 public final String title;
 public

    Entry(String title) {
 this.title = title;
 }
 }
  2. .BJO"DUJWJUZ public class MainActivity extends AppCompatActivity {
 …
 MainComponent mainComponent

    = DaggerMainComponent.create();
 
 Optional<Entry> entry = mainComponent.entry();
 Log.e(“entry”, entry.or(new Entry(“default")).title); …
 } w EFGBVMUͱදࣔ͞ΕΔ
  3. .BJO"DUJWJUZ public class MainActivity extends AppCompatActivity {
 …
 Optional<Entry> entry

    = mainComponent.entry();
 Log.e(“entry”, entry.or(new Entry(“default")).title); …
 } w FOUSZͱදࣔ͞ΕΔ
  4. 0QUJPOBMΛίϯετϥΫλ Ͱड͚औΔΫϥε public class EntryManager {
 private final Entry mEntry;


    @Inject
 public EntryManager(Optional<Entry> entryOptional) {
 mEntry = entryOptional.or(new Entry("default"));
 }
 
 public String getTitle() {
 return mEntry.title;
 }
 }
  5. &OUSZΛఏڙ͠ͳ͍ $PNQPOFOU @Subcomponent
 public interface EmptyComponent {
 void inject(MainActivity activity);


    @Subcomponent.Builder
 interface Builder {
 EmptyComponent build();
 }
 }
  6. &OUSZΛఏڙ͢Δ $PNQPOFOU @Subcomponent(modules = SavedEntryModule.class)
 public interface SavedEntryComponent {
 void

    inject(MainActivity activity);
 @Subcomponent.Builder
 interface Builder {
 SavedEntryComponent build();
 }
 }
  7. "DUJWJUZ public class MainActivity extends AppCompatActivity {
 @Inject EntryManager mEntryManager;


    …
 DaggerMainComponent
 .create()
 .emptyComponent()
 .build()
 .inject(this);
 Log.e("title", mEntryManager.getTitle()); // default
 
 DaggerMainComponent
 .create()
 .savedEntryComponent()
 .build()
 .inject(this);
 Log.e("title", mEntryManager.getTitle()); // saved
 }