2016-07-25 4 views
0

質問は件名にありますが、もう一度やり直してみます:Dagger2が@SingletonとカスタムSopesを扱う方法に違いはありますか?

Dagger2が@SingletonとカスタムSopeを扱う方法に違いはありますか?

また、あるスコープで注釈が付けられたクラスは、別のスコープ(またはスコープなし)として公開するのが便利なのでしょうか、またはプロバイダメソッドを書く必要がありますか?

答えて

2

Dagger2が@SingletonとカスタムSopeを扱う方法には違いはありません。

はちょうど私たちが確認する必要があり、我々はここで

@Scope 
@Retention(RetentionPolicy.RUNTIME) 
public @interface User { 
} 


@Module 
public class TwitterModule { 
    private final String user; 

    public TwitterModule(String user) { 
     this.user = user; 
    } 

    @Provides 
    @User 
    Tweeter provideTweeter(TwitterApi twitterApi) { 
     return new Tweeter(twitterApi, user); 
    } 

    @Provides 
    @User 
    Timeline provideTimeline(TwitterApi twitterApi) { 
     return new Timeline(twitterApi, user); 
    } 

} 


@Module 
public class NetworkModule { 

    @Provides 
    @Singleton 
    OkHttpClient provideOkHttpClient() { 
     return new OkHttpClient(); 
    } 

    @Provides 
    @Singleton 
    TwitterApi provideTwitterApi(OkHttpClient okHttpClient) { 
     return new TwitterApi(okHttpClient); 
    } 

} 


@Singleton 
@Component(modules = {NetworkModule.class}) 
public interface ApiComponent { 

    TwitterApi api(); 

    TwitterComponent twitterComponent(TwitterModule twitterModule); 
} 

@User 
@Subcomponent(modules = {TwitterModule.class}) 
public interface TwitterComponent { 

    TwitterApplication app(); 
} 


public class MainActivity extends AppCompatActivity { 

    private static final String TAG = MainActivity.class.getSimpleName(); 

    TwitterComponent twitterComponentForUserOne,twitterComponentForUserTwo; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     ApiComponent apiComponent = DaggerApiComponent.create(); 

     twitterComponentForUserOne = apiComponent.twitterComponent(new TwitterModule("Amit Shekhar")); 

     twitterComponentForUserTwo = apiComponent.twitterComponent(new TwitterModule("Sumit Shekhar")); 

     // use twitterComponentOne and twitterComponentTwo for two users independently 

    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     twitterComponentForUserOne = null; 
     twitterComponentForUserTwo = null; 
    } 
} 

@user

使用しているとしましょう、我々はそのユーザのtwitterComponentを必要としないとき。私はonDestroy()でここでやっているようにガベージコレクトされるようにnullを代入する必要があります。

最後にすべてがコンポーネントに依存します。アプリケーションクラスにコンポーネントのインスタンスがある場合、アプリケーションのライフサイクル全体でガベージコレクションされません。

関連する問題