Created
February 27, 2020 02:17
-
-
Save amirulzin/f7208f0352820148f9b0da8f6528c4b1 to your computer and use it in GitHub Desktop.
Dagger constructor injection for AAC ViewModel without module (MIT license)
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
import androidx.annotation.NonNull; | |
import androidx.lifecycle.ViewModel; | |
import androidx.lifecycle.ViewModelProvider; | |
import javax.inject.Inject; | |
import javax.inject.Provider; | |
public class DaggerViewModelFactory<VM extends ViewModel> implements ViewModelProvider.Factory { | |
private final Provider<VM> provider; | |
@Inject | |
public DaggerViewModelFactory(@NonNull Provider<VM> provider) { | |
this.provider = provider; | |
} | |
@NonNull | |
@Override | |
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { | |
//noinspection unchecked | |
return (T) 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
public class SomeActivity extends AppCompatActivity { | |
@Inject | |
DaggerViewModelFactory<SomeViewModel> vmFactory; | |
@Override | |
protected void onCreate(@Nullable Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
dependencyInjection(); | |
SomeViewModel vm = new ViewModelProvider(this, vmFactory).get(SomeViewModel.class); | |
} | |
private void dependencyInjection() { | |
((SomeApplication) getApplication()) | |
.getSomeAppComponent() | |
.inject(this); | |
} | |
} |
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
public class SomeViewModel extends ViewModel { | |
@Inject | |
public SomeViewModel(){} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment