https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
n

nrobi

11/30/2020, 1:58 PM
[KMM] Those who are sharing ViewModels and using SwiftUI on iOS, how do you approach disposing background jobs? I’m exposing a
dispose()
and calling it from my
ObservableObject
’s
deinit
method (which represents my view’s state and essentially wraps my ViewModel while publishing the state to the view). Any thoughts if there is a better way?
1
z

zsperske

11/30/2020, 2:38 PM
I've been thinking about this too. Curious why you prefer deinit to using
onDisappear
?
n

nrobi

11/30/2020, 2:59 PM
@zsperske that way I don't have to expose neither the vm nor an additional function to the view
👍 1
t

Thomas

11/30/2020, 3:02 PM
I am using deinit for cancelling the view model coroutine scope. Using onDisappear is not possible, because when that is called the view can still reappear, just like Android onPause/onStop. The deinit is not ideal though, as it does not work well with SwiftUI sheets.
👍 1
z

zsperske

11/30/2020, 3:49 PM
what happens with sheets?
t

Thomas

11/30/2020, 4:34 PM
When dismissing a sheet the deinit does not get called for ObservableObjects used in that sheet. At least that is what is happening in my project.
a

Arkadii Ivanov

12/01/2020, 4:42 PM
AFAIK SwiftUI may retain gone views just in case they are reused later. I observed this behaviour a while ago.
51 Views