Inject ViewModel using Dagger 2 + Kotlin + ViewModel

后端 未结 6 1392
-上瘾入骨i
-上瘾入骨i 2021-02-07 07:07
class SlideshowViewModel : ViewModel() {

@Inject lateinit var mediaItemRepository : MediaItemRepository

fun init() {
    What goes here?
}

So I\'m tr

6条回答
  •  深忆病人
    2021-02-07 07:36

    I wrote a library that should make this more straightforward and way cleaner, no multibindings or factory boilerplate needed, while also giving the ability to further parametrise the ViewModel at runtime: https://github.com/radutopor/ViewModelFactory

    @ViewModelFactory
    class UserViewModel(@Provided repository: Repository, userId: Int) : ViewModel() {
    
        val greeting = MutableLiveData()
    
        init {
            val user = repository.getUser(userId)
            greeting.value = "Hello, $user.name"
        }    
    }
    

    In the view:

    class UserActivity : AppCompatActivity() {
        @Inject
        lateinit var userViewModelFactory2: UserViewModelFactory2
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_user)
            appComponent.inject(this)
    
            val userId = intent.getIntExtra("USER_ID", -1)
            val viewModel = ViewModelProviders.of(this, userViewModelFactory2.create(userId))
                .get(UserViewModel::class.java)
    
            viewModel.greeting.observe(this, Observer { greetingText ->
                greetingTextView.text = greetingText
            })
        }
    }
    

提交回复
热议问题