在ViewModel中实现Dagger,从而调用另一个类

时间:2019-04-27 16:42:54

标签: android kotlin dagger-2

这是我尝试在应用中实现匕首的第一次尝试,但是我对此仍然停留了一段时间。我正在尝试在此处实施Dagger,请耐心等待。

这是我的应用程序的当前代码:

class Login : AppCompatActivity(), LifecycleOwner {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    private fun clickLogin() {

        var loginViewModel = LoginViewModel()
        loginViewModel = ViewModelProviders.of(this).get(LoginViewModel::class.java)
        loginViewModel.getLoginObservable(params)!!.observe(this, Observer { myLoginSession ->
            }
        )
    }
}


class LoginViewModel: ViewModel() {

    private var loginObservable: LiveData<MyLoginSession>? = null
    private var dbRepository: DbRepository? = null

    fun getLoginObservable(params: Map<String, String>): LiveData<MyLoginSession>? {
        dbRepository = DbRepository()

        loginObservable = NetworkRepository.getInstance().login(userType, email, password)
        return loginObservable
    }
}

public class NetworkRepository {

    private WebService webService;
    private static NetworkRepository networkRepository;

    private NetworkRepository(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(WebService.SERVER_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        webService = retrofit.create(WebService.class);
    }

    public synchronized static NetworkRepository getInstance(){
        if (networkRepository == null){
            networkRepository = new NetworkRepository();
        }
        return networkRepository;
    }

    public LiveData<MyLoginSession> login(int userType, String email, String password){

        final MutableLiveData<MyLoginSession> data = new MutableLiveData<>();

        HashMap<String, Object> params = new HashMap<>();
        params.put("userType",userType);
        params.put("email",email);
        params.put("password",password);

        webService.login(params).enqueue(new Callback<MyLoginSession>() {
            @Override
            public void onResponse(Call<MyLoginSession> call, Response<MyLoginSession> response) {
                Log.v(TAG,"Response code: " + response.code());
                }

            @Override
            public void onFailure(Call<MyLoginSession> call, Throwable t) {
                data.setValue(null);
            }
        });

        return data;
    }
}

现在,我正在尝试使用Dagger实现DI,以便首先在NetworkRepository下进行函数登录。

所以我首先在下面添加了这些依赖项:

ext {
    daggerVer = "2.22.1"
}

implementation "com.google.dagger:dagger:$daggerVer"
annotationProcessor "com.google.dagger:dagger-compiler:$daggerVer"
compileOnly 'javax.annotation:javax.annotation-api:1.3.2'

并如下创建AppModule类:

@Module
public class AppModule {

    @Provides
    WebService providesWebService(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        return new Retrofit.Builder()
                .baseUrl(WebService.SERVER_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(WebService.class);
    }
}

并将我的NetworkRepository类更改为以下内容:

@Singleton
public class NetworkRepository {
    private WebService webService;

    @Inject
    private NetworkRepository(WebService webService){
        this.webService = webService;
    }

    public LiveData<MyLoginSession> login(int userType, String email, String password){

            final MutableLiveData<MyLoginSession> data = new MutableLiveData<>();

            HashMap<String, Object> params = new HashMap<>();
            params.put("userType",userType);
            params.put("email",email);
            params.put("password",password);

            webService.login(params).enqueue(new Callback<MyLoginSession>() {
                @Override
                public void onResponse(Call<MyLoginSession> call, Response<MyLoginSession> response) {
                    Log.v(TAG,"Response code: " + response.code());
                    }

                @Override
                public void onFailure(Call<MyLoginSession> call, Throwable t) {
                    data.setValue(null);
                }
            });

            return data;
        }
}

还有我的LoginViewModel

@Singleton
class LoginViewModel: ViewModel() {

    @Inject lateinit var networkRepository: NetworkRepository

    @Inject
    fun getLoginObservable(params: Map<String,String>):LiveData<MyLoginSession>{
        DaggerAppComponent.builder().build.buildWebService(this)
        loginObservable = networkRepository.login(userType, email, password)
        return loginObservable
    }
}

如果我上面的尝试使用Dagger的代码令人困惑,则很可能(显然)是由于我在尝试在应用中实现Dagger时遇到的困惑。.我经历了无数的教程,而我却遇到了一些小问题在这些教程的项目中实现Dagger时,当我尝试在自己的应用中实现Dagger时,一切都变得一团糟。

我无法编译上面的代码,因为它返回Unresolved reference: DaggerAppComponent;这个问题应该在构建应用程序后解决,但是不能解决,所以我敢肯定我的Dagger代码还有其他问题。

我曾几次尝试回溯并重新执行Dagger实现,但现在我走了一圈,我的确感觉就像把Dagger放在心里。

1 个答案:

答案 0 :(得分:0)

我以前有这个问题。我使用以下代码对其进行了修复:

apply plugin: 'kotlin-kapt'

dependencies {
    def daggerVer = 2.22.1 // or latest version

    implementation "com.google.dagger:dagger:$daggerVer"
    implementation "com.google.dagger:dagger-android-support:$daggerVer"
    kapt "com.google.dagger:dagger-android-processor:$daggerVer"
    kapt "com.google.dagger:dagger-compiler:$daggerVer"
}

请参阅DaggerAppComponent not created