我已经阅读了更多关于Dagger2的内容,我发现它与Butterknife
类似,因为当我需要使用它时,我创建了一个模块,并使用:
((MyApp) getApplication()).createAppComponent().inject(this);
使用,例如,这个:
@Inject
RegisterPresenter presenter;
但我不明白如何使用构造函数注入。我有一个案例(使用模型 - 视图 - 演示者):
private Register.View view;
private RegisterModel model;
private StorageModel storageModel;
private DatabaseModel databaseModel;
private Uri compressPath;
List<String > stringList;
String uid;
@Inject
public RegisterPresenter() {
model = new RegisterModel(this);
storageModel = new StorageModel(this);
databaseModel = new DatabaseModel(this);
}
是对的吗?或者我需要这样做?
@Inject
public RegisterPresenter(RegisterModel model, StorageModel storageModel, DatabaseModel databaseModel) {
this.model = model;
this.storageModel = storageModel;
this.databaseModel = databaseModel;
}
因为如果我使用第二个代码,在我的活动(View)中我需要这样做:
protected void onResume() {
super.onResume();
presenter.setView(this);
}
那么如何构建演示者呢?或者如果我需要在Activity中创建它,从视图传递模块是否正确?
编辑:这些是我的模特:
public class FirebaseModel implements Model, FirebaseAuth.AuthStateListener {
FirebaseAuth auth;
Presenter presenter;
FirebaseUser user;
@Inject
public FirebaseModel(Presenter presenter) {
this.presenter = presenter;
auth = FirebaseAuth.getInstance();
}
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
user = auth.getCurrentUser();
presenter.updateUser(user);
}
@Override
public void loadUser() {
auth.addAuthStateListener(this);
}
}
public class StorageModel implements Register.Storage,OnCompleteListener <UploadTask.TaskSnapshot>{
Register.Presenter presenter;
StorageReference storage;
@Inject
public StorageModel(Register.Presenter presenter) {
this.presenter = presenter;
storage = FirebaseStorage.getInstance().getReferenceFromUrl("gs://firebase-happypark.appspot.com");
}
@Override
public void onTryToUpdateUser(Uri path,String uid) {
if(path != null) {
StorageReference riversRef = storage.child("uid").child("ImgProfile/" + path.getLastPathSegment());
UploadTask uploadTask = riversRef.putFile(path);
Log.d("ssd", "sto qua");
uploadTask.addOnCompleteListener(this);
}
}
//UNNECESSARY
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
presenter.onUploadCompleted();
} else {
presenter.onUploadError(task.getException());
}
}
}
谢谢
答案 0 :(得分:0)
Presenter会是这样的:
public class RegisterPresenter implements RegisterContract.Presenter {
private Register.View view;
private RegisterModel model;
private StorageModel storageModel;
private DatabaseModel databaseModel;
private Uri compressPath;
List<String > stringList;
String uid;
@Inject
public RegisterPresenter(Register.View view, RegisterModel model, StorageModel storageModel, DatabaseModel databaseModel) {
this.view = view;
this.model = model;
this.storageModel = storageModel;
this.databaseModel = databaseModel;
}
@Override
public void someMethodFromContract(){}
//or anything else you have in mind
}
然后在onResume中调用它
presenter.someMethodFromContract();