简体   繁体   中英

Found a dependency cycle in dagger 2

I try to provide fragment with DatePickerDialog , but when i use the BasicInfoFragment as argument it cause the error : Found a dependency cycle why that happen ?!

@Module
class ActivityModule(val activity: AppCompatActivity) {

    @Provides
    fun provideActivity() = activity

    @Provides
    @ActivityContext
    fun provideContext(): Context = activity

    // [...]
    @Provides
    fun provideDatePickerDialog(basicInfoFragment: BasicInfoFragment): 
    DatePickerDialog {
        return DatePickerDialog(activity, basicInfoFragment, 1999, 9, 9)
    }
}

Fragment code :

class BasicInfoFragment @Inject constructor()
    : BaseFragment(), BasicInfoMvpView , 
      LabelledSpinner.OnItemChosenListener, 
      DatePickerDialog.OnDateSetListener {

    @Inject
    lateinit var datePickerDialog: DatePickerDialog

    @Inject
    lateinit var mPresenter: BasicInfoMvpPresenter<BasicInfoMvpView>

    // user info
    private lateinit var gender: DataManager.UserGender
    private var birthOfDate: Long = 0L


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.base_user_info_layout, container, false)

        activityComponent?.let {
            it.inject(this)
            mPresenter.onAttach(this)
        }

        return view
    }

    override fun onDateSet(dataPicker: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
        birthOfDate = GregorianCalendar(year, month, dayOfMonth).timeInMillis
    }
}

In your provideDatePickerDialog you need a BasicInfoFragment , but then when you also try to inject a DatePickerDialog in BasicInfoFragment . Hence the chicken or egg problem - to create either of them you need the other.

Something else to take into account: in the constructor of the DateTimePicker you really need the DatePickerDialog.OnDateSetListener not the BasicInfoFragment .

Solution 1

Change the provideDatePickerDialog as follows

@Provides
fun provideDatePickerDialog(basicInfoFragment: BasicInfoFragment): 
DatePickerDialog {
    return DatePickerDialog(activity)
}

then set the listener and the date in the fragment. See documentation here

Solution 2

Don't provide the DatePickerDialog with Dagger but instead create it in the BasicInfoFragment with this line:

DatePickerDialog(activity, this, 1999, 9, 9)

This way you will also eliminate other possible issues and confusions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM