Hello! Samples for iOS use SwiftUI, but it’s only ...
# mvikotlin
s
Hello! Samples for iOS use SwiftUI, but it’s only for iOS 13+ and in most cases is not suitable for production. I would like to see the most primitive example of use with ordinary
UIViewController
. More specifically, working with Lifecycle, subscription for state changes and sending events. If I just copy
LifecycleRegistryExt
and
LifecycleWrapper
and do:
override func viewDidLoad() {
self.viewLifecycle = LifecycleRegistry()
self.controller?.controller.onViewCreated(...)
self.controller?.lifecycle.start()
}
override func viewDidAppear(_ animated: Bool) {
self.viewLifecycle?.resume()
}
override func viewDidDisappear(_ animated: Bool) {
self.viewLifecycle?.destroy()
}
deinit {
self.controller?.lifecycle.stop()
}
Would this be the right approach?
a
hey, I think that this would work better -
viewDidAppear -> resume
viewDidDisappear -> stop
deinit -> destroy
s
There are different types of lifecycle :) ViewLifecycle usually has a shorter lifespan (from experience on Android. I’m not very good on iOS).
a
there is a diagram for Lifecycle and you can map it to corresponding
UIViewController
events.

https://static.packt-cdn.com/products/9781783550814/graphics/0814OT_06_02.jpg

s
It looks like I did it right 🤔 Controller’s lifecycle coincides with the life cycle of the screen,
ViewLifecycle
with the life cycle of the view
a
deinit
is called when object instance is deallocated.
s
Yes.
viewDidUnload
is deprecated, and I don’t know a more suitable method than
deinit
to signal that a screen no longer exists.
a
onStop
should happen before
onDestroy
, because
onStop
signals that
View
is no longer visible, but
onDestroy
signals that
View
no longer exists.
in your case you are calling
onDestroy
in
viewDidDisappear
, but as you see in
UIViewController
lifecycle it can reappear.
so when it reappears you will call
onResume
and lifecycle will be messed up.
a
because you will have ->
onStart -> onResume -> onDestroy -> onStop
hm, interesting then I would like to know why it is used like that. 😄
a
Hello! With UIKit you can use just one single
Lifecycle
object for both controller and view. A similar (an MVI-ish approach, not MVIKotlin) sample can be found here: https://github.com/badoo/Reaktive/blob/master/sample-ios-app/sample-ios-app/ViewController.swift So the mapping is as follows:
viewDidLoad
->
onViewCreated
videWillAppear
->
onStart
viewWillDisappear
->
onStop
deinit
->
onViewDestroy
+
onDestroy
This is because in swift UI view can be destroyed when moved to backstack
onDesappear
, but its
Controller
is not destroyed and will be reused later. In UIKit there is no such a behaviour.
👍🏻 2
s
Thanks for the detailed answer 😊