-
Notifications
You must be signed in to change notification settings - Fork 173
init commit #42
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
init commit #42
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| package otus.homework.dagger | ||
|
|
||
| import android.app.Application | ||
| import otus.homework.dagger.di.* | ||
| import otus.homework.dagger.di.AppModule | ||
|
|
||
| class App : Application() { | ||
|
|
||
| override fun onCreate() { | ||
| super.onCreate() | ||
| appComponent = DaggerAppComponent.builder().appModule(AppModule(this)).build() | ||
| activityComponent = DaggerActivityComponent.factory().create(appComponent) | ||
| fragmentReceverComponent = DaggerFragmentReceiverComponent.factory().create(activityComponent) | ||
| fragmentProducerComponent = DaggerFragmentProducerComponent.factory().create(activityComponent) | ||
| } | ||
|
|
||
| companion object { | ||
| lateinit var appComponent: AppComponent | ||
| lateinit var activityComponent: ActivityComponent | ||
| lateinit var fragmentReceverComponent: FragmentReceiverComponent | ||
| lateinit var fragmentProducerComponent: FragmentProducerComponent | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| package otus.homework.dagger | ||
|
|
||
| import androidx.lifecycle.MutableLiveData | ||
|
|
||
| class ColorFlow { | ||
| var colorObserver = MutableLiveData<Int>() | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,15 @@ | ||
| package ru.otus.daggerhomework | ||
| package otus.homework.dagger | ||
|
|
||
| import androidx.appcompat.app.AppCompatActivity | ||
| import android.os.Bundle | ||
| import android.widget.Toast | ||
| import androidx.appcompat.app.AppCompatActivity | ||
|
|
||
| class MainActivity : AppCompatActivity() { | ||
|
|
||
| override fun onCreate(savedInstanceState: Bundle?) { | ||
| super.onCreate(savedInstanceState) | ||
| setContentView(R.layout.activity_main) | ||
| App.appComponent.injectInto(this) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Опять же, если у тебя компонент создается в Application и по смыслу и по названию относиться к Application, то его инжектить можно только в Application, если тебе нужны его сущности то выстраивай иерархию |
||
| Toast.makeText(App.appComponent.context, "context.toString()", Toast.LENGTH_LONG).show() | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| package otus.homework.dagger | ||
|
|
||
| import android.content.Context | ||
| import androidx.lifecycle.ViewModel | ||
| import androidx.lifecycle.ViewModelProvider | ||
|
|
||
| class MyViewModelFactory constructor(private val context: Context) : ViewModelProvider.Factory { | ||
|
|
||
| override fun <T : ViewModel> create(modelClass: Class<T>): T { | ||
| return if (modelClass.isAssignableFrom(ViewModelProducer::class.java)) { | ||
| ViewModelProducer(context = context, colorGenerator = ColorGeneratorImpl()) as T | ||
| } else if (modelClass.isAssignableFrom(ViewModelReceiver::class.java)) { | ||
| ViewModelReceiver(context) as T | ||
| } else { | ||
| throw IllegalArgumentException("ViewModel Not Found") | ||
| } | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,22 @@ | ||
| package ru.otus.daggerhomework | ||
| package otus.homework.dagger | ||
|
|
||
| import android.content.Context | ||
| import android.widget.Toast | ||
| import androidx.fragment.app.FragmentActivity | ||
| import androidx.lifecycle.ViewModel | ||
| import java.lang.RuntimeException | ||
| import javax.inject.Inject | ||
|
|
||
| class ViewModelProducer( | ||
| private val colorGenerator: ColorGenerator, | ||
| private val context: Context | ||
| ) { | ||
| ) : ViewModel() { | ||
| @Inject | ||
| lateinit var observer: ColorFlow | ||
|
|
||
| fun generateColor() { | ||
| if (context !is FragmentActivity) throw RuntimeException("Здесь нужен контекст активити") | ||
| Toast.makeText(context, "Color sent", Toast.LENGTH_LONG).show() | ||
| observer.colorObserver.value = colorGenerator.generateColor() | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,18 @@ | ||
| package ru.otus.daggerhomework | ||
| package otus.homework.dagger | ||
|
|
||
| import android.app.Application | ||
| import android.content.Context | ||
| import android.widget.Toast | ||
| import androidx.fragment.app.FragmentActivity | ||
| import androidx.lifecycle.ViewModel | ||
| import java.lang.RuntimeException | ||
| import javax.inject.Inject | ||
|
|
||
| class ViewModelReceiver( | ||
| private val context: Context | ||
| ) { | ||
| ) : ViewModel() { | ||
| @Inject | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А почему здесь инжект в поле? Инжекти в конструктор и ВМ создавай через фабрику, это предпочтительный способ, к тому же я не совсем понял как у тебя вообще код компилируется если здесь нет мембер инжектора |
||
| lateinit var observer: ColorFlow | ||
|
|
||
| fun observeColors() { | ||
| if (context !is Application) throw RuntimeException("Здесь нужен контекст апликейшена") | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| package otus.homework.dagger.di | ||
|
|
||
| import android.content.Context | ||
| import dagger.Component | ||
| import dagger.Module | ||
| import dagger.Provides | ||
| import otus.homework.dagger.ColorFlow | ||
| import otus.homework.dagger.FragmentProducer | ||
| import otus.homework.dagger.FragmentReceiver | ||
| import javax.inject.Scope | ||
|
|
||
| @ActivityScope | ||
| @Component(dependencies = [AppComponent::class], modules = [ActivityModule::class]) | ||
| interface ActivityComponent { | ||
| var context: Context | ||
|
|
||
| fun injectInto(producer: FragmentProducer) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Зачем эти методы? Если у тебя компонент на активити то писать мембер инжектор методы на фрагмент это бед практис. Если тебе во фрагменте нужна какая то сущность, которая предоставляется ActivityComponent и его модулями, то для этого как раз и используются сабкомпоненты app -> activity -> fragment |
||
| fun injectInto(receiver: FragmentReceiver) | ||
|
|
||
| @Component.Factory | ||
| interface Factory { | ||
| fun create(appComponent: AppComponent): ActivityComponent | ||
| } | ||
| } | ||
|
|
||
| @Module | ||
| class ActivityModule { | ||
| @get:Provides | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Этот модуль можно убрать. Добавь инжект аннотацию над ColorFlow |
||
| @ActivityScope | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Скоуп здесь не нужен |
||
| var observer = ColorFlow() | ||
| } | ||
|
|
||
| @Scope | ||
| annotation class ActivityScope | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package otus.homework.dagger.di | ||
|
|
||
| import android.content.Context | ||
| import dagger.Component | ||
| import dagger.Module | ||
| import dagger.Provides | ||
| import otus.homework.dagger.App | ||
| import otus.homework.dagger.MainActivity | ||
| import javax.inject.Singleton | ||
|
|
||
| @Singleton | ||
| @Component(modules = [AppModule::class]) | ||
| interface AppComponent { | ||
| var context: Context | ||
|
|
||
| fun injectInto(activity: MainActivity) | ||
| } | ||
|
|
||
| @Module | ||
| internal class AppModule(var app: App) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Вместо конструктора модуля нужны использовать BindsInstance |
||
| @Singleton | ||
| @Provides | ||
| fun provideContext(): Context { | ||
| return app.applicationContext | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| package otus.homework.dagger.di | ||
|
|
||
| import android.content.Context | ||
| import androidx.lifecycle.ViewModelProvider | ||
| import androidx.lifecycle.ViewModelStoreOwner | ||
| import dagger.Component | ||
| import dagger.Module | ||
| import dagger.Provides | ||
| import otus.homework.dagger.MyViewModelFactory | ||
| import otus.homework.dagger.ViewModelProducer | ||
| import otus.homework.dagger.ViewModelReceiver | ||
| import javax.inject.Scope | ||
|
|
||
| @FragmentScope | ||
| @Component(dependencies = [ActivityComponent::class], modules = [FragmentReceiverModule::class]) | ||
| interface FragmentReceiverComponent { | ||
| var context: Context | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Зачем эта проперти? Выглядит как какая-то смесь между сабкомпонентами и компонент депенденсис. Если ты выбрал сабкомпоненты то эти провижен методы/проперти не нужны |
||
| var vmReceiver: ViewModelReceiver | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. И эта |
||
|
|
||
| @Component.Factory | ||
| interface Factory { | ||
| fun create(activityComponent: ActivityComponent): FragmentReceiverComponent | ||
| } | ||
| } | ||
|
|
||
| @Module | ||
| class FragmentReceiverModule(var context: Context) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Не используй конструктор модуля, это bad practice тк ты не можешь использовать статические Provides методы и модуль теперь содержит стейт. |
||
|
|
||
| @Provides | ||
| @FragmentScope | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. То же самое про скоуп |
||
| fun provideVMReceiver(owner: ViewModelStoreOwner) : ViewModelReceiver { | ||
| return ViewModelProvider(owner, MyViewModelFactory(context))[ViewModelReceiver::class.java] | ||
| } | ||
| } | ||
|
|
||
| @FragmentScope | ||
| @Component(dependencies = [ActivityComponent::class], modules = [FragmentProducerModule::class]) | ||
| interface FragmentProducerComponent { | ||
|
|
||
| var context: Context | ||
| var vmProducer: ViewModelProducer | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Аналогичные вопросы. Эти проперти не нужны |
||
|
|
||
| @Component.Factory | ||
| interface Factory { | ||
| fun create(activityComponent: ActivityComponent): FragmentProducerComponent | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А зачем ему в аргументах ActivityComponent если у тебя FragmentProducerComponent должен быть сабкомпонентом у ActivityComponent? в ActivityComponent должен появится провижен метод который отдает FragmentProducerComponent.Factory |
||
| } | ||
| } | ||
| @Module | ||
| class FragmentProducerModule(var context: Context) { | ||
|
|
||
| @Provides | ||
| @FragmentScope | ||
| fun provideVMReceiver(owner: ViewModelStoreOwner) : ViewModelProducer { | ||
| return ViewModelProvider(owner, MyViewModelFactory(context))[ViewModelProducer::class.java] | ||
| } | ||
| } | ||
|
|
||
| @Scope | ||
| annotation class FragmentScope | ||
This file was deleted.
This file was deleted.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Зачем тебе эти компоненты на уровне апликейшена? это чревато утечками памяти, тк в этих комопнентах лежит ссылка на фрагменты. Создавай их прямо в активити/фрагментах