Skip to content

Instantly share code, notes, and snippets.

View Nimrodda's full-sized avatar

Nimrod Dayan Nimrodda

View GitHub Profile
class DetailViewModel(
private val handle: SavedStateHandle
) : ViewModel() {
fun loadData() {
val id = handle["id"] ?: "default"
// Load data for ID...
}
}
class DetailActivity : AppCompatActivity() {
private val viewModel: DetailViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Use viewModel here
}
}
class DetailViewModel(
private val githubApi: GithubApi,
private val handle: SavedStateHandle
) : ViewModel() {
fun loadData() {
val id = handle["id"] ?: "default"
viewModelScope.launch {
val response = githubApi.getCommit(id)
// Handle response
}
class DetailViewModelFactory(
private val githubApi: GithubApi,
owner: SavedStateRegistryOwner,
defaultArgs: Bundle? = null
) : AbstractSavedStateViewModelFactory(owner, defaultArgs) {
override fun <T : ViewModel> create(
key: String,
modelClass: Class<T>,
handle: SavedStateHandle
): T {
class DetailActivity : AppCompatActivity() {
private val githubApi = GithubApi()
private val viewModel by viewModels { DetailViewModelFactory(githubApi, this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Use viewModel here
viewModel.loadData()
}
class ViewModelFactory @Inject constructor(
private val creators: MutableMap<Class<out ViewModel>, Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return creators[modelClass]?.get() as? T
?: throw IllegalArgumentException("The requested ViewModel isn't bound")
}
}
@Module
abstract class DetailModule {
@Binds
@IntoMap
@ViewModelKey(DetailViewModel::class)
abstract fun bindViewModel(viewModel: DetailViewModel): ViewModel
}
class DetailViewModel @Inject constructor(
private val githubApi: GithubApi,
private val handle: SavedStateHandle
) : ViewModel() {
fun loadData() {
val id = handle["id"] ?: "default"
viewModelScope.launch {
val response = githubApi.getCommit(id)
// Handle response
}
compileOnly("com.squareup.inject:assisted-inject-annotations-dagger2:0.3.3")
kapt("com.squareup.inject:assisted-inject-processor-dagger2:0.3.3")
class DetailViewModel @AssistedInject constructor(
private val githubApi: GithubApi,
@Assisted private val handle: SavedStateHandle
) : ViewModel() {
fun loadData() {
val id = handle["id"] ?: "default"
viewModelScope.launch {
val response = githubApi.getCommit(id)
// Handle response
}