Search code examples
androidkotlinandroid-fragmentsandroid-activitydagger-hilt

Activity-Fragment Communication w/ Hilt


I have an app with a single activity but with many Fragments. I am using ViewModel for my Activity-Fragment communication. Lately, I am using Hilt, and I am having a problem now communicating between my activity and fragments.

My Viewmodel

@HiltViewModel
class AppViewModel @Inject internal constructor(
): ViewModel() {

    private var _data = MutableLiveData<String>()
    val data: LiveData<String>
        get() = _data
    fun insertData(dataStr: String) {
        _data.value = dataStr
    }
}

My MainActivity

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private val mViewModel: AppViewModel by viewModels()
    private var dataString: String? = null

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

        mViewModel.data.observe(this, {
            dataString = it
        })
    }
}

One of my Fragments

@AndroidEntryPoint
class ReportFragment : Fragment() {

    private val reportViewModel: ReportViewModel by viewModels()
    private val appViewModel: AppViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View { 
        ...
        appViewModel.insertData("Hello")
        ...
    }
}

When I run the app, I am getting null as a result of data. Any solution to solve this?


Solution

  • Not sure if this is the exact issue, but you get the ViewModel inside your fragment using by activityViewModels<AppViewModel> and not by viewModels

    EDIT:

    Also, I just noticed you are using an internal constructor. Try using only inject constructor once and let me know if it fixed it for you :)