iT邦幫忙

2021 iThome 鐵人賽

DAY 18
0

在 Dagger 裡需要以下四大重要的 annotation:

  1. @Inject : 這其實是 Java 的物件,代表物件會被外部設定
  2. @Component : @Module 跟需要 dependency 的物件中間的橋樑
  3. @Module : 標注在 class 上,代表這個 class 包含著一到多個標註了 @Provide 的 function
  4. @Provide : 標注在 function 上,代表這個 function 會提供 dependency

在 build.gradle 向 dependencies 添加( https://github.com/google/dagger/releases 可以找到最新版本的 Dagger):

dependencies {
    implementation 'com.google.dagger:dagger:2.21'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.21'
}

UserRepository:

public class UserRepository {
    private final UserLocalDataSource userLocalDataSource;
    private final UserRemoteDataSource userRemoteDataSource;

    @Inject
    public UserRepository(UserLocalDataSource userLocalDataSource, UserRemoteDataSource userRemoteDataSource) {
        this.userLocalDataSource = userLocalDataSource;
        this.userRemoteDataSource = userRemoteDataSource;
    }
}

UserLocalDataSource:

public class UserLocalDataSource {
    @Inject
    public UserLocalDataSource() {}
}

public class UserRemoteDataSource {
    private final LoginRetrofitService loginRetrofitService;

    @Inject
    public UserRemoteDataSource(LoginRetrofitService loginRetrofitService) {
        this.loginRetrofitService = loginRetrofitService;
    }
}

LoginViewModel:

public class LoginViewModel {
    private final UserRepository userRepository;

    @Inject
    public LoginViewModel(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
}

ApplicationComponent:

@Component(modules = NetworkModule.class)
public interface ApplicationComponent {
    // 注入 LoginActivity
    void inject(LoginActivity loginActivity);
}

MyApplication:

public class MyApplication extends Application {
    ApplicationComponent appComponent = DaggerApplicationComponent.create();
}

LoginActivity:

public class LoginActivity extends Activity {
    @Inject
    LoginViewModel loginViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ((MyApplication) getApplicationContext()).appComponent.inject(this);
        super.onCreate(savedInstanceState);
    }
}

NetworkModule:

@Module
public class NetworkModule {
    @Provides
    public LoginRetrofitService provideLoginRetrofitService() {
        return new Retrofit.Builder()
                .baseUrl("https://example.com")
                .build()
                .create(LoginService.class);
    }
}

謝謝大家願意花時間閱讀,小弟弟我在此鞠躬/images/emoticon/emoticon41.gif


上一篇
[Lesson17] MVP
下一篇
[Lesson19] View Binding
系列文
刮掉Web Development的我,與撿到的Android Development30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言