viewModelScope is cancelled in viewPager
Asked Answered
L

1

8

there are fragments in viewPager and each fragment has a viewModel.

when viewpager's current item changes ,fragment is destroyed ,viewModel onCleared is called and viewModelScope is cancelled

there are 2 problems , first after returning back to same fragment, viewModelScope is cancelled and can't launch any coroutines. second when viewPager's current item is changing , the launched coroutine is cancelled.

how can i solve this issues?

i use FragmentStatePagerAdapter with BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT and OffscreenPageLimit is the default value.

Lenhart answered 17/2, 2021 at 11:35 Comment(0)
E
0

If you want to do something during the application run lifecycle. You could use ProcessLifecycleOwner. like below.

ProcessLifecycleOwner.get().launch {
 // Do what you want.
}

Or even you can use shared ViewModel for each framents of viewpage.

============================== Deprecated ==================

use GlobeScope.launch{}

Edvard answered 17/2, 2021 at 11:49 Comment(1)
This is actually one of the way i solved it, although i'd prefer a better solution.Inchmeal

© 2022 - 2024 — McMap. All rights reserved.