Skip to content

Commit

Permalink
Introduce Dagger Hilt ViewModel extension
Browse files Browse the repository at this point in the history
  • Loading branch information
takahirom committed Oct 3, 2020
1 parent 4c862ee commit 1bec337
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
10 changes: 10 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ android {
sourceCompatibility 1.8
targetCompatibility 1.8
}
kotlinOptions {
jvmTarget = '1.8'
}

buildTypes {
release {
Expand All @@ -36,6 +39,10 @@ dependencies {
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"

// Hilt ViewModel
implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02'
kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha02'

// For instrumentation tests
androidTestImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"
Expand All @@ -47,8 +54,11 @@ dependencies {
testImplementation "org.robolectric:robolectric:4.4"

implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDependency
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.1'

implementation 'androidx.fragment:fragment-ktx:1.2.5'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
testImplementation 'junit:junit:4.12'
Expand Down
16 changes: 13 additions & 3 deletions app/src/main/java/com/github/takahirom/hiltsample/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import android.app.Application
import android.content.Context
import android.os.Bundle
import android.os.PersistableBundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.ViewModel
import androidx.room.*
import dagger.Module
import dagger.Provides
Expand Down Expand Up @@ -33,12 +36,11 @@ class App : Application() {

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject
lateinit var videoPlayer: VideoPlayer
private val videoPlayerViewModel: VideoPlayerViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
videoPlayer.play()
videoPlayerViewModel.play()
}
}

Expand Down Expand Up @@ -91,6 +93,14 @@ class JustDaggerActivity : AppCompatActivity() {
}
}

class VideoPlayerViewModel @ViewModelInject constructor(
private val videoPlayer: VideoPlayer
) : ViewModel() {
fun play() {
videoPlayer.play()
}
}

class VideoPlayer @Inject constructor(
private val database: VideoDatabase
) {
Expand Down

0 comments on commit 1bec337

Please sign in to comment.