0
0

More than 3 years have passed since last update.

[SavedStateHandle] やっぱりDaggerとうまく付き合う

Last updated at Posted at 2020-04-21

以前 SavedStateHandle を DI する方法について記事を書きましたが、今は正直以下の方法でも良いのではないかと思っています。

class MyViewModel(handle: SavedStateHandle) : ViewModel() {
    @Inject
    lateinit var myRepository: MyRepository

    val myData: LiveData<MyData> = liveData {
        emitSource(myRepository.getMyData())
    }
}
class MyFragment : Fragment() {
    private val viewModel by viewModels<MyViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        (requireActivity().applicationContext as App)
            .component
            .inject(viewModel)
    }
}

SavedStateHandle はデフォルトの ViewModelFactory におまかせして、それ以外のコンポーネントをフィールドインジェクションでセットする方法です。

テストはしていません。
以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0