Skip to content

Commit

Permalink
Create Hilt Navigation artifact.
Browse files Browse the repository at this point in the history
Add androidx.hilt:hilt-navigation and androidx.hilt:hilt-navigation-fragment containing APIs for using @HiltViewModel and Hilt's ViewModelFactory with AndroidX Navigation.
The APIs will allow users to retrieve a HiltViewModelFactory whose view model owner and saved state owner is the NavBackStackEntry. Additionally it provide a kotlin extension, `hiltNavGraphViewModels` which mimics `navGraphViewModels`.

These artifacts essentially tackle:
* google/dagger#2152
* google/dagger#2166

Test: HiltNavGraphViewModelLazyTest
Relnote: Provide APIs for using @HiltViewModel with Navigation.

Change-Id: I00e675363f5af3922205a30f4670a4c33877a7b3
  • Loading branch information
danysantiago committed Jan 12, 2021
1 parent 70dfe75 commit 7bc8576
Show file tree
Hide file tree
Showing 22 changed files with 612 additions and 1 deletion.
2 changes: 1 addition & 1 deletion buildSrc/build_dependencies.gradle
Expand Up @@ -26,7 +26,7 @@ build_versions.kotlin = "1.4.21"
build_versions.kotlin_coroutines = "1.4.1"
build_versions.ksp = "1.4.20-dev-experimental-20201204"

build_versions.hilt = "2.29.1-alpha"
build_versions.hilt = "DEV-SNAPSHOT"

def agpOverride = System.getenv("GRADLE_PLUGIN_VERSION")
if (agpOverride != null) {
Expand Down
3 changes: 3 additions & 0 deletions hilt/hilt-navigation-fragment/api/api_lint.ignore
@@ -0,0 +1,3 @@
// Baseline format: 1.0
MissingNullability: androidx.hilt.navigation.fragment.HiltNavGraphViewModelLazyKt#hiltNavGraphViewModels(androidx.fragment.app.Fragment, int):
Missing nullability on method `hiltNavGraphViewModels` return
9 changes: 9 additions & 0 deletions hilt/hilt-navigation-fragment/api/current.txt
@@ -0,0 +1,9 @@
// Signature format: 4.0
package androidx.hilt.navigation.fragment {

public final class HiltNavGraphViewModelLazyKt {
method @MainThread public static inline <reified VM extends androidx.lifecycle.ViewModel> kotlin.Lazy<? extends VM>! hiltNavGraphViewModels(androidx.fragment.app.Fragment, @IdRes int navGraphId);
}

}

@@ -0,0 +1,9 @@
// Signature format: 4.0
package androidx.hilt.navigation.fragment {

public final class HiltNavGraphViewModelLazyKt {
method @MainThread public static inline <reified VM extends androidx.lifecycle.ViewModel> kotlin.Lazy<? extends VM>! hiltNavGraphViewModels(androidx.fragment.app.Fragment, @IdRes int navGraphId);
}

}

Empty file.
9 changes: 9 additions & 0 deletions hilt/hilt-navigation-fragment/api/restricted_current.txt
@@ -0,0 +1,9 @@
// Signature format: 4.0
package androidx.hilt.navigation.fragment {

public final class HiltNavGraphViewModelLazyKt {
method @MainThread public static inline <reified VM extends androidx.lifecycle.ViewModel> kotlin.Lazy<? extends VM>! hiltNavGraphViewModels(androidx.fragment.app.Fragment, @IdRes int navGraphId);
}

}

65 changes: 65 additions & 0 deletions hilt/hilt-navigation-fragment/build.gradle
@@ -0,0 +1,65 @@
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


import androidx.build.LibraryGroups
import androidx.build.LibraryVersions
import androidx.build.Publish

import static androidx.build.dependencies.DependenciesKt.*

plugins {
id("AndroidXPlugin")
id("com.android.library")
id("kotlin-android")
id("kotlin-kapt")
id("dagger.hilt.android.plugin")
}

android {
defaultConfig {
testInstrumentationRunner "androidx.hilt.navigation.fragment.TestRunner"
}
}

dependencies {
api(KOTLIN_STDLIB)
api(project(":hilt:hilt-navigation"))
api("androidx.navigation:navigation-fragment-ktx:2.3.2")

androidTestImplementation(projectOrArtifact(":fragment:fragment-testing"))
androidTestImplementation(ANDROIDX_TEST_EXT_JUNIT)
androidTestImplementation(ANDROIDX_TEST_CORE)
androidTestImplementation(ANDROIDX_TEST_RUNNER)
androidTestImplementation(ANDROIDX_TEST_RULES)
androidTestImplementation(TRUTH)
androidTestImplementation(HILT_ANDROID)
androidTestImplementation(HILT_ANDROID_TESTING)
kaptAndroidTest(HILT_COMPILER)
androidTestImplementation(project(":internal-testutils-runtime"))
androidTestImplementation(project(":internal-testutils-navigation"), {
exclude group: 'androidx.navigation', module: 'navigation-common-ktx'
})
}

androidx {
name = "Android Navigation Fragment Hilt Extension"
publish = Publish.SNAPSHOT_AND_RELEASE
mavenVersion = LibraryVersions.HILT
mavenGroup = LibraryGroups.HILT
inceptionYear = "2021"
description = "Android Navigation Fragment Hilt Extension"
}
23 changes: 23 additions & 0 deletions hilt/hilt-navigation-fragment/src/androidTest/AndroidManifest.xml
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2017 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="androidx.navigation.fragment.ktx">
<application>
<activity android:name="androidx.hilt.navigation.fragment.NavGraphActivity" />
</application>
</manifest>
@@ -0,0 +1,149 @@
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package androidx.hilt.navigation.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.hilt.navigation.fragment.test.R
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.navigation.findNavController
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.testutils.withActivity
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import javax.inject.Inject

/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

@LargeTest
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class HiltNavGraphViewModelLazyTest {

@get:Rule
val testRule = HiltAndroidRule(this)

@Test
fun sameViewModelAcrossFragments() {
with(ActivityScenario.launch(NavGraphActivity::class.java)) {
val navController = withActivity { findNavController(R.id.nav_host_fragment) }
val firstFragment: TestVMFragment = withActivity {
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_fragment)!!
navHostFragment.childFragmentManager.primaryNavigationFragment as TestVMFragment
}
val viewModel = withActivity { firstFragment.viewModel }
val savedStateViewModel = withActivity { firstFragment.savedStateViewModel }
assertThat(viewModel).isNotNull()
assertThat(savedStateViewModel).isNotNull()

// First assert that we don't have any default value since the
// navigation graph wasn't sent any arguments
val initialState: String? = savedStateViewModel.savedStateHandle["test"]
assertThat(initialState).isNull()

// Now set arguments
savedStateViewModel.savedStateHandle.set("test", "test")

// Navigate to the second destination and ensure it
// gets the same ViewModels and data
withActivity {
navController.navigate(R.id.second_destination)
}
val secondFragment: TestVMFragment = withActivity {
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_fragment)!!
navHostFragment.childFragmentManager.primaryNavigationFragment as TestVMFragment
}
assertThat(secondFragment.viewModel)
.isSameInstanceAs(viewModel)
assertThat(secondFragment.savedStateViewModel)
.isSameInstanceAs(savedStateViewModel)
val savedValue: String? = secondFragment.savedStateViewModel
.savedStateHandle["test"]
assertThat(savedValue).isEqualTo("test")

// Now recreate the Activity and ensure that when we
// first request the nav graph ViewModel on the second destination
// that we get the same ViewModel and data back
recreate()
val recreatedFragment: TestVMFragment = withActivity {
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_fragment)!!
navHostFragment.childFragmentManager.primaryNavigationFragment as TestVMFragment
}
assertThat(recreatedFragment.viewModel)
.isSameInstanceAs(viewModel)
assertThat(recreatedFragment.savedStateViewModel)
.isSameInstanceAs(savedStateViewModel)
val recreatedValue: String? = recreatedFragment.savedStateViewModel
.savedStateHandle["test"]
assertThat(recreatedValue).isEqualTo("test")
}
}
}

@AndroidEntryPoint
class NavGraphActivity : FragmentActivity(R.layout.activity_nav_graph)

@AndroidEntryPoint
class TestVMFragment : Fragment() {
val viewModel: TestViewModel by hiltNavGraphViewModels(R.id.vm_graph)
val savedStateViewModel: TestSavedStateViewModel by hiltNavGraphViewModels(R.id.vm_graph)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return View(activity)
}
}

@HiltViewModel
class TestViewModel @Inject constructor() : ViewModel()

@HiltViewModel
class TestSavedStateViewModel @Inject constructor(
val savedStateHandle: SavedStateHandle
) : ViewModel()
@@ -0,0 +1,32 @@
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package androidx.hilt.navigation.fragment

import android.app.Application
import android.content.Context
import androidx.test.runner.AndroidJUnitRunner
import dagger.hilt.android.testing.HiltTestApplication

class TestRunner : AndroidJUnitRunner() {
override fun newApplication(
cl: ClassLoader?,
className: String?,
context: Context?
): Application {
return super.newApplication(cl, HiltTestApplication::class.java.name, context)
}
}
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2021 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nav_host_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="androidx.navigation.fragment.NavHostFragment"
app:defaultNavHost="true"
app:navGraph="@navigation/vm_graph" />
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2021 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<navigation
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/vm_graph"
app:startDestination="@+id/start_destination">
<fragment
android:id="@+id/start_destination"
android:name="androidx.hilt.navigation.fragment.TestVMFragment">
<argument
android:name="test"
android:defaultValue="first"/>
</fragment>
<fragment
android:id="@+id/second_destination"
android:name="androidx.hilt.navigation.fragment.TestVMFragment">
<argument
android:name="test"
android:defaultValue="second" />
</fragment>
</navigation>

0 comments on commit 7bc8576

Please sign in to comment.