Home » Android » android – mvvm using dagger2 with ViewModelFactory, dont understand default injection-Exceptionshub

android – mvvm using dagger2 with ViewModelFactory, dont understand default injection-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I’m studying mvvm with AAC examples “https://github.com/android/architecture-samples“.
hard to understand, I found something not understandable.
the project has ViewModel and ViewModelFactory.
the point I wanna know is that how the ViewModel of TaskFragment is injected by DefaultTasksRepository.

class TasksFragment : DaggerFragment() {

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    private val viewModel by viewModels<TasksViewModel> { viewModelFactory }
}
class TasksViewModel @Inject constructor(
    private val tasksRepository: TasksRepository
) : ViewModel() {
}
class DefaultTasksRepository @Inject constructor(
    @TasksRemoteDataSource private val tasksRemoteDataSource: TasksDataSource,
    @TasksLocalDataSource private val tasksLocalDataSource: TasksDataSource,
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : TasksRepository {
}
interface TasksRepository {

    suspend fun getTasks(forceUpdate: Boolean = false): Result<List<Task>>

    suspend fun getTask(taskId: String, forceUpdate: Boolean = false): Result<Task>

    suspend fun saveTask(task: Task)

    suspend fun completeTask(task: Task)

    suspend fun completeTask(taskId: String)

    suspend fun activateTask(task: Task)

    suspend fun activateTask(taskId: String)

    suspend fun clearCompletedTasks()

    suspend fun deleteAllTasks()

    suspend fun deleteTask(taskId: String)
}
How to&Answers:
  1. DefaultTasksRepository @Inject constructor(), this has been registered in dagger so that we can use its reference from anywhere.

  2. TasksViewModel @Inject constructor(), this will create TasksViewModel reference but before that it will create instance of DefaultTasksRepository and will pass into constructor of TasksViewModel.

  3. Then you can inject TasksViewModel and use anywhere.