Dagger2 Optional bindings

8928b5277aa7234dbca4ff782952343a?s=47 funnelbit
November 28, 2016

Dagger2 Optional bindings

8928b5277aa7234dbca4ff782952343a?s=128

funnelbit

November 28, 2016
Tweet

Transcript

  1. 6.

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

    Entry(String title) {
 this.title = title;
 }
 }
  2. 9.

    .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. 12.

    .BJO"DUJWJUZ public class MainActivity extends AppCompatActivity {
 …
 Optional<Entry> entry

    = mainComponent.entry();
 Log.e(“entry”, entry.or(new Entry(“default")).title); …
 } w FOUSZͱදࣔ͞ΕΔ
  4. 15.

    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. 16.

    &OUSZΛఏڙ͠ͳ͍ $PNQPOFOU @Subcomponent
 public interface EmptyComponent {
 void inject(MainActivity activity);


    @Subcomponent.Builder
 interface Builder {
 EmptyComponent build();
 }
 }
  6. 17.

    &OUSZΛఏڙ͢Δ $PNQPOFOU @Subcomponent(modules = SavedEntryModule.class)
 public interface SavedEntryComponent {
 void

    inject(MainActivity activity);
 @Subcomponent.Builder
 interface Builder {
 SavedEntryComponent build();
 }
 }
  7. 19.

    "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
 }