InsertKoinIO / koin

Koin - a pragmatic lightweight dependency injection framework for Kotlin & Kotlin Multiplatform
https://insert-koin.io
Apache License 2.0
8.76k stars 695 forks source link

SavedStateHandle get null after app return from background #1880

Closed Evonne0103 closed 1 month ago

Evonne0103 commented 1 month ago

Describe the bug

have SavedStateHandle within ShareViewModel, and in HomeFragment get the ShareViewModel from MainActivity, also pass the ShareViewModel to HomeViewModel, the problem is get null from SavedStateHandle after app relaunch from background

In the Modules:

val viewModelModule = module {
    viewModel { ShareViewModel(get()) }
    viewModel { (shareViewModel: ShareViewModel) ->
        HomeViewModel(
            shareViewModel
        )
    }
}
class ShareViewModel(
    val stateHandle: SavedStateHandle
) : ViewModel(), KoinComponent {
 val sharedResp: MutableLiveData<Resp?> = stateHandle.getLiveData(KEY_RESP, null)

   fun getSharedResp(): Resp? {
        return sharedResp.value
    }

   fun updateResp(resp: Resp) {
        sharedResp.value = resp
    }
}
class MainActivity : BaseActivity(R.layout.activity_main) {
    private val shareViewModel: ShareViewModel by viewModel()
}
  class HomeFragment : BaseFragment<FragmentHomeBinding>() {

    private val shareViewModel: ShareViewModel by activityViewModel()
    private val viewModel by viewModel<HomeViewModel> {
        parametersOf(shareViewModel)
    }
class HomeViewModel(
    private val shareViewModel: ShareViewModel,
) 

To Reproduce Steps to reproduce the behavior:

  1. Mobile open "Don't keep activities" toggle and run the app
  2. put app into background
  3. relaunch the app
  4. the SavedStateHandle get null, but keep doing this circle about 3 times the SavedStateHandle get value back

Expected behavior the SavedStateHandle shouldn't be null after relaunch app from background

Koin module and version: koin-core:3.4.3 lifecycle-viewmodel-savedstate:2.5.1