Я использую AbstractSavedStateViewModelFactory , чтобы использовать SavedStateHandle в модели представления с непустым конструктором.Но я получаю Исключение из незаконного состояния, в котором говорится, что оно уже связано с владельцем жизненного цикла (см. Ниже)Когда вместо этого я использую SavedStateViewModelFactory
, он работает нормально, но не поддерживает непустые конструкторы и является конечным классом.
TestStateAFragment
class TestStateAFragment : Fragment() {
companion object {
fun newInstance() : TestStateAFragment {
val fragment = TestStateAFragment()
val bundle = Bundle()
bundle.putParcelable("arg_a", TestState.TestStateA)
fragment.arguments = bundle
return fragment
}
}
private lateinit var viewModel : TestStateAViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val factory = TestStateAViewModelFactory(activity as SavedStateRegistryOwner)
viewModel = ViewModelProviders.of(this, factory).get(TestStateAViewModel::class.java)
}
}
TestStateAViewModel
class TestStateAViewModel(val savedStateHandle: SavedStateHandle) : ViewModel() {
var countStateObserver : BehaviorRelay<Int> = BehaviorRelay.create<Int>()
private var count : Int = 0
set(value) {
field = value
savedStateHandle.set("count", field)
countStateObserver.accept(field)
}
init {
savedStateHandle.get<Int>("count")?.let {
count = it
}
}
fun incrementCount() {
count += 1
}
fun decrementCount() {
count -= 1
}
}
TestStateAViewModelFactory
class TestStateAViewModelFactory(
savedStateRegistryOwner: SavedStateRegistryOwner,
bundle : Bundle? = null
) : AbstractSavedStateViewModelFactory(savedStateRegistryOwner, bundle) {
override fun <T : ViewModel?> create(
key: String,
modelClass: Class<T>,
handle: SavedStateHandle
): T {
return TestStateAViewModel(handle) as T
}
}
Исключение:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.lifecycleviewmodel, PID: 14295
java.lang.IllegalStateException: Already attached to lifecycleOwner
at androidx.lifecycle.SavedStateHandleController.attachToLifecycle(SavedStateHandleController.java:43)
at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:67)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:177)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:145)
at com.example.lifecycleviewmodel.fragment.states.a.TestStateAFragment.onCreate(TestStateAFragment.kt:47)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2586)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:838)
at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1197)
at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1080)
at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:119)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1866)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
at com.example.lifecycleviewmodel.TestActivity.onStart(TestActivity.kt:34)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1470)
at android.app.Activity.performStart(Activity.java:7170)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3071)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Может кто-нибудь, пожалуйстауказать, где проблема?Спасибо.