0
問題在於這個問題,但我會再次重複一遍:Dagger2對待@Singleton和自定義sopes有什麼不同嗎?
Dagger2對待@Singleton和自定義sopes的方式有什麼不同嗎?另外,如果一個類是用某個範圍註釋的,是否有一種方便的方式將它作爲一個不同的範圍(或無範圍的)公開,還是需要編寫一個提供者方法?
問題在於這個問題,但我會再次重複一遍:Dagger2對待@Singleton和自定義sopes有什麼不同嗎?
Dagger2對待@Singleton和自定義sopes的方式有什麼不同嗎?另外,如果一個類是用某個範圍註釋的,是否有一種方便的方式將它作爲一個不同的範圍(或無範圍的)公開,還是需要編寫一個提供者方法?
Dagger2對待@Singleton和自定義皰疹的方式沒有區別。
假設我們使用@user
@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;
}
}
這裏只是我們必須確保,當我們不需要twitterComponent該用戶。我們必須分配null,以便在onDestroy()中進行垃圾回收。
最後,一切都取決於組件,如果您在Application類中有一個組件實例,那麼它將不會在整個應用程序生命週期中被垃圾收集。