Last active
January 7, 2020 00:27
-
-
Save ktchernov/a1edcbc8040f30a2e323e05b0efb4035 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.github.ktchernov | |
import androidx.lifecycle.ViewModel | |
import androidx.lifecycle.ViewModelProvider | |
import javax.inject.Provider | |
abstract class ViewModelFactory <VM : ViewModel> protected constructor( | |
private val provider: Provider<VM>) : ViewModelProvider.Factory { | |
override fun <T : ViewModel> create(modelClass: Class<T>): T | |
= modelClass.cast(provider.get())!! | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage example: | |
package io.github.ktchernov.view | |
import androidx.lifecycle.ViewModelProviders | |
import dagger.android.support.DaggerFragment | |
import io.github.ktchernov.ExampleViewModel | |
import io.github.ktchernov.ExampleViewModelFactory | |
// .. | |
class ExampleFragment : DaggerFragment() { | |
@Inject | |
internal lateinit var viewModelFactory: ExampleViewModelFactory | |
private lateinit var viewModel: ExampleViewModel | |
override fun onCreateView(inflater: LayoutInflater, | |
container: ViewGroup?, | |
savedInstanceState: Bundle?): View? { | |
return inflater.inflate(R.layout.your_fragment, container, false).also { | |
bindViewModel() | |
} | |
} | |
private fun bindViewModel() { | |
val viewModelProviders = ViewModelProviders.of(this, viewModelFactory) | |
viewModel = viewModelProviders[ExampleViewModel::class.java] | |
// bind your view model to your view using LiveData/Rx/Callbacks/etc. | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage example: | |
package io.github.ktchernov | |
import androidx.lifecycle.ViewModel | |
import javax.inject.Inject | |
import javax.inject.Provider | |
import io.github.ktchernov.ViewModelFactory | |
// .. | |
@YourFragmentScope | |
class ExampleViewModelFactory @Inject internal constructor( | |
provider: Provider<ExampleViewModel>) | |
: ViewModelFactory<ExampleViewModel>(provider) | |
@YourFragmentScope | |
class ExampleViewModel @Inject internal constructor( | |
private val injectedParamA: A, | |
private val injectedParamB: B, | |
) : ViewModel() { | |
/// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment