Slide 1

Slide 1 text

Kotlin Multiplatform Architecture Kevin Galligan

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

Touchlab

Slide 4

Slide 4 text

Community community!

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

SHARED ARHICTECTURE

Slide 7

Slide 7 text

Mobile & Web Architecture, not UI

Slide 8

Slide 8 text

Shared UI == Failure!

Slide 9

Slide 9 text

Shared Loigc == Computers

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

Web is more difficult No SQL :(

Slide 12

Slide 12 text

Advocate for new standards I want SQL again

Slide 13

Slide 13 text

https://hacks.mozilla.org/

Slide 14

Slide 14 text

mobile is MUCH simpler

Slide 15

Slide 15 text

Why Kotlin?

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

Modern Language

Slide 18

Slide 18 text

No content

Slide 19

Slide 19 text

Community Excitement

Slide 20

Slide 20 text

Best Tools

Slide 21

Slide 21 text

Smooth Interop

Slide 22

Slide 22 text

Optional Sharing Low risk. No Big Decisions.

Slide 23

Slide 23 text

“Everything Should Be Made as Simple as Possible, But Not Simpler” - Albert Einstein Maybe?

Slide 24

Slide 24 text

Status

Slide 25

Slide 25 text

Q3 Q2 Q4 Q1 Q2 2018 2019 0 .6 v0.7 v0.8 v0.8.2 v0.9.3 IDE tooling! Coroutines?

Slide 26

Slide 26 text

Q3 Q2 Q4 Q1 Q2 2018 2019 0 .6 v0.7 v0.8 v0.8.2 v0.9.3 IDE tooling! Coroutines? K/N 1.0, Kotlin 1.3 Gradle 4.10+ Android Studio

Slide 27

Slide 27 text

Q3 Q2 Q4 Q1 Q2 2018 2019 0 .6 v0.7 v0.8 v0.8.2 v0.9.3 IDE tooling! Coroutines? K/N 1.0, Kotlin 1.3 Gradle 4.10+ Android Studio MT Coroutines! Other samples/libraries Production deployments

Slide 28

Slide 28 text

Q3 Q2 Q4 Q1 Q2 2018 2019 0 .6 v0.7 v0.8 v0.8.2 v0.9.3 IDE tooling! Coroutines? K/N 1.0, Kotlin 1.3 Gradle 4.10+ Android Studio MT Coroutines! Other samples/libraries Production deployments Paid license/debugger Reactive Library Big Production Apps Webassembly stuff?

Slide 29

Slide 29 text

SHARED CODE FOR ANDROID & IOS

Slide 30

Slide 30 text

Common

Slide 31

Slide 31 text

Common mainThread?

Slide 32

Slide 32 text

expect val mainThread:Boolean

Slide 33

Slide 33 text

expect val mainThread:Boolean actual val mainThread: Boolean get() = Looper.myLooper() === Looper.getMainLooper()

Slide 34

Slide 34 text

expect val mainThread:Boolean actual val mainThread: Boolean get() = Looper.myLooper() === Looper.getMainLooper() actual val mainThread: Boolean get() = NSThread.isMainThread()

Slide 35

Slide 35 text

expect val mainThread:Boolean actual val mainThread: Boolean get() = Looper.myLooper() === Looper.getMainLooper() actual val mainThread: Boolean get() = NSThread.isMainThread() actual val mainThread: Boolean = true

Slide 36

Slide 36 text

expect fun currentTimeMillis():Long expect fun backgroundTask(backJob:()-> B, mainJob:(B) -> Unit) expect fun backgroundTask(backJob:()->Unit) expect fun networkBackgroundTask(backJob:()->Unit) expect fun initContext():NativeOpenHelperFactory expect fun goFreeze(a:T):T expect fun T.freeze2(): T expect fun simpleGet(url:String):String expect fun logException(t:Throwable) expect fun settingsFactory(): Settings.Factory expect fun createUuid():String

Slide 37

Slide 37 text

expect class Date { fun toLongMillis():Long } expect class DateFormatHelper(format:String){ fun toDate(s:String):Date fun format(d:Date):String }

Slide 38

Slide 38 text

actual class Date(val date:java.util.Date) { actual fun toLongMillis(): Long = date.time } actual class DateFormatHelper actual constructor(format: String) { val dateFormatter = object : ThreadLocal(){ override fun initialValue(): DateFormat = SimpleDateFormat(format) } actual fun toDate(s: String): Date = Date(dateFormatter.get()!!.parse(s)) actual fun format(d: Date): String = dateFormatter.get()!!.format(d.date) }

Slide 39

Slide 39 text

fun initPlatformClient( staticFileLoader: (filePrefix: String, fileType: String) -> String?, analyticsCallback: (name: String, params: Map) -> Unit, clLogCallback: (s: String) -> Unit) {

Slide 40

Slide 40 text

fun initPlatformClient( staticFileLoader: (filePrefix: String, fileType: String) -> String?, analyticsCallback: (name: String, params: Map) -> Unit, clLogCallback: (s: String) -> Unit) { AppContext.initPlatformClient ({filePrefix, fileType -> loadAsset("${filePrefix}.${fileType}")}, {name: String, params: Map -> val event = CustomEvent(name) //Loop Answers.getInstance().logCustom(event) }, { Log.w("MainApp", it) })

Slide 41

Slide 41 text

let appContext = AppContext() appContext.doInitPlatformClient(staticFileLoader: loadAsset, analyticsCallback: analyticsCallback, clLogCallback: csLog) func loadAsset(filePrefix:String, fileType:String) -> String?{ do{ let bundleFile = Bundle.main.path(forResource: filePrefix, ofType: fileType) return try String(contentsOfFile: bundleFile!) } catch { return nil } }

Slide 42

Slide 42 text

Common

Slide 43

Slide 43 text

JVM Native Common

Slide 44

Slide 44 text

JVM Native Common Framework

Slide 45

Slide 45 text

JVM Native Common Framework

Slide 46

Slide 46 text

JVM Native Common Android Stuff Framework iOS Stuff

Slide 47

Slide 47 text

JVM Native Common

Slide 48

Slide 48 text

JVM Native Common Ktor-JVM Ktor-Native Ktor

Slide 49

Slide 49 text

More Info and Tutorials https://github.com/touchlab/KotlinMultiplatformStuff

Slide 50

Slide 50 text

DROIDCON WITH KOTLIN MULTIPLATFORM

Slide 51

Slide 51 text

Funky Code Testbed

Slide 52

Slide 52 text

Funky Code Testbed Kotlin in 2014!

Slide 53

Slide 53 text

Droidcon NYC & SF

Slide 54

Slide 54 text

SQLite Knarch.db Android iOS

Slide 55

Slide 55 text

SQLite Knarch.db SQLDelight Android iOS

Slide 56

Slide 56 text

SQLite Knarch.db SQLDelight Logic! Reactive (LiveData) Android iOS

Slide 57

Slide 57 text

SQLite Knarch.db SQLDelight Logic! Reactive (LiveData) Android iOS

Slide 58

Slide 58 text

SQLite Knarch.db SQLDelight MP Settings Logic! Reactive (LiveData) Android iOS

Slide 59

Slide 59 text

val evenLiveData:EventLiveData init { val query = goFreeze(AppContext.dbHelper. queryWrapper.sessionQueries. sessionById(sessionId)) evenLiveData = EventLiveData(query) } fun shutDown(){ evenLiveData.removeListener() }

Slide 60

Slide 60 text

val evenLiveData:EventLiveData init { val query = goFreeze(AppContext.dbHelper. queryWrapper.sessionQueries. sessionById(sessionId)) evenLiveData = EventLiveData(query) } fun shutDown(){ evenLiveData.removeListener() }

Slide 61

Slide 61 text

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { eventViewModel.eventModel.evenLiveData. observe(viewLifecycleOwner, Observer { dataRefresh(it) }) return initView(inflater, container) }

Slide 62

Slide 62 text

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { eventViewModel.eventModel.evenLiveData. observe(viewLifecycleOwner, Observer { dataRefresh(it) }) return initView(inflater, container) }

Slide 63

Slide 63 text

fun registerForChanges(proc:(sessionInfo:SessionInfo)->Unit){ eventObserver = object : Observer{ override fun onChanged(t: SessionInfo?){ if(t != null) proc(t) } } eventModel.evenLiveData.observeForever(eventObserver!!) }

Slide 64

Slide 64 text

viewModel = EventViewModel(sessionId: sessionId) viewModel.registerForChanges(proc: updateUi)

Slide 65

Slide 65 text

viewModel = EventViewModel(sessionId: sessionId) viewModel.registerForChanges(proc: updateUi) func updateUi(sessionInfo:SessionInfo) -> KotlinUnit{ self.sessionInfo = sessionInfo styleButton() updateAllUi() return KotlinUnit() }

Slide 66

Slide 66 text

Droidcon App Kotlin Multiplatform https://www.youtube.com/watch?v=YAeDK3Ei0Lk https://github.com/touchlab/DroidconKotlin/ Now with 0.9.3!

Slide 67

Slide 67 text

KOTLINCONF WITH KOTLIN MULTIPLATFORM (OBV)

Slide 68

Slide 68 text

Settings Android iOS Ktor

Slide 69

Slide 69 text

Settings Android iOS Ktor DataRepository

Slide 70

Slide 70 text

Settings Android iOS Ktor DataRepository SessionDetailsPresenter

Slide 71

Slide 71 text

Settings Android iOS Ktor DataRepository SessionDetailsPresenter SessionDetailsView

Slide 72

Slide 72 text

interface SessionDetailsView : BaseView { fun updateView(isFavorite: Boolean, session: SessionModel) fun setupRatingButtons(rating: SessionRating?) fun setRatingClickable(clickable: Boolean) } override fun updateView(isFavorite: Boolean, session: SessionModel) { collapsingToolbar.title = session.title speakersTextView.text = session.speakers.joinToString(separator = ", ") { it.fullName } timeTextView.text = session.timeString detailsTextView.text = listOfNotNull(session.roomText, session.category).joinToString(", ") descriptionTextView.text = session.descriptionText val online = context?.let { it.isConnected?.and(!it.isAirplaneModeOn) } ?: false for (button in listOf(votingButtonsLayout, favoriteButton)) { func updateView(isFavorite: Bool, session: SessionModel) { titleLabel.text = session.title let startsAt = session.startsAt let endsAt = session.endsAt if (startsAt != nil && endsAt != nil) { timeLabel.text = KotlinPair(first: startsAt, second: endsAt).toReadableString() } let image = UIImage(named: isFavorite ? "star_full" : "star_empty")! favoriteButton.image = image

Slide 73

Slide 73 text

Settings Android iOS Ktor DataRepository SessionDetailsPresenter SessionDetailsView

Slide 74

Slide 74 text

KotlinConf App https://github.com/JetBrains/kotlinconf-app

Slide 75

Slide 75 text

Which?

Slide 76

Slide 76 text

STATE

Slide 77

Slide 77 text

3 Ecosystems JVM, JS, and Native

Slide 78

Slide 78 text

Kotlin/Native State Rules

Slide 79

Slide 79 text

Rule #1 Live state belongs to 1 thread

Slide 80

Slide 80 text

Rule #2 Frozen state can be shared by threads

Slide 81

Slide 81 text

No threading primitives No “synchronized”, “volatile”, etc

Slide 82

Slide 82 text

Runtime Safety Kotlin/Native can verify safe mutability

Slide 83

Slide 83 text

JVM/JS? See Kotlinconf keynote

Slide 84

Slide 84 text

Short term pain Tradeoff for future

Slide 85

Slide 85 text

How does Kotlin know?!

Slide 86

Slide 86 text

FROZEN!

Slide 87

Slide 87 text

FROZEN!

Slide 88

Slide 88 text

Runtime Designation AKA a flag

Slide 89

Slide 89 text

all the code you’ve ever written not frozen frozen

Slide 90

Slide 90 text

all the code you’ve ever written not frozen frozen

Slide 91

Slide 91 text

One-way operation No unfreeze()

Slide 92

Slide 92 text

Freezes everything

Slide 93

Slide 93 text

class TalkExamples{ var justCountingStuff:Int = 0 init { backgroundCall { //do something justCountingStuff++ }.freeze() } }

Slide 94

Slide 94 text

class TalkExamples{ var justCountingStuff:Int = 0 init { backgroundCall { //do something justCountingStuff++ }.freeze() } }

Slide 95

Slide 95 text

Usually OK Data objects should be immutable

Slide 96

Slide 96 text

Global state more difficult Service object, large memory state

Slide 97

Slide 97 text

Passing State

Slide 98

Slide 98 text

DetachedObjectGraph(TransferMode.SAFE) { ListData("asdf") }

Slide 99

Slide 99 text

val data = ListData("asdf") DetachedObjectGraph(TransferMode.SAFE) { data }

Slide 100

Slide 100 text

private val stateBox: AtomicReference> = AtomicReference( DetachedObjectGraph(mode = TransferMode.SAFE, producer = { mutableListOf() as Any }) ) private val lock = NSLock() internal fun withLockDetached(proc: (MutableList) -> MutableList) { lock.lock() try { stateBox.value = DetachedObjectGraph(mode = TransferMode.SAFE, producer = { val dataList = stateBox.value.attach() as MutableList proc(dataList) as Any }) } finally { lock.unlock() } }

Slide 101

Slide 101 text

Atomics! Mutable immutable

Slide 102

Slide 102 text

AtomicInt/AtomicLong

Slide 103

Slide 103 text

AtomicReference Update with frozen objects

Slide 104

Slide 104 text

val lambdas = AtomicReference(null) fun initPlatformClient( staticFileLoader: (filePrefix: String, fileType: String) -> String?, analyticsCallback: (name: String, params: Map) -> Unit, clLogCallback: (s: String) -> Unit) { lambdas.value = PlatformLambdas( staticFileLoader, analyticsCallback, clLogCallback).freeze() }

Slide 105

Slide 105 text

data class FrozenData( val someCount:AtomicInt, val someString:String, val someOtherState:AtomicReference ) data class OtherState( val otherCount:Int, val otherString:String )

Slide 106

Slide 106 text

val frozenData = FrozenData( AtomicInt(1), "asdf", AtomicReference( OtherState( 1, "qwert") ) ).freeze()

Slide 107

Slide 107 text

val frozenData = FrozenData( AtomicInt(1), "asdf", AtomicReference( OtherState( 1, "qwert") ) ).freeze()

Slide 108

Slide 108 text

fun update(frozenData: FrozenData){ frozenData.someCount.increment() val otherState = frozenData.someOtherState.value val updated = otherState.copy(otherCount = otherState.otherCount+1) frozenData.someOtherState.value = updated.freeze() }

Slide 109

Slide 109 text

Stately! v0.3.1~ish

Slide 110

Slide 110 text

Multiplatform Definitions • freeze() method and frozen info • Atomics (Int, Long, Reference) • K/N state-related annotations (@ThreadLocal/ @SharedImmutable)

Slide 111

Slide 111 text

Multithreaded Collections Built on atomics

Slide 112

Slide 112 text

val cowList = frozenCopyOnWriteList() val sharedList = frozenLinkedList() val coiSharedList = frozenLinkedList(stableIterator = true) val sharedMap = frozenHashMap() val lruRemovedCount = AtomicInt(0) val lruCache = frozenLruCache(5) { lruRemovedCount.increment() }

Slide 113

Slide 113 text

Why? If you have to ask…

Slide 114

Slide 114 text

No content

Slide 115

Slide 115 text

Changing Architectures Coroutines, libraries, best practices

Slide 116

Slide 116 text

THREADING

Slide 117

Slide 117 text

Workers like Executor

Slide 118

Slide 118 text

Passing State similar to DetachedObjectGraph

Slide 119

Slide 119 text

Until Coroutines MT coroutines will largely replace Worker

Slide 120

Slide 120 text

Coroutines and State? we’ll see

Slide 121

Slide 121 text

LIBRARIES

Slide 122

Slide 122 text

Jetbrains • Ktor • Kotlinx.Coroutines • Kotlinx.io • Atomic-fu

Slide 123

Slide 123 text

Community • Sqldelight • Knarch.db • Multiplatform Settings • Stately • OKIO2 (developing)

Slide 124

Slide 124 text

GETTING STARTED

Slide 125

Slide 125 text

Intellij EAP Sample project templates!

Slide 126

Slide 126 text

No content

Slide 127

Slide 127 text

Build Samples Conference apps, several others

Slide 128

Slide 128 text

Kotlin/Native Docs Learn threads and state

Slide 129

Slide 129 text

Join the Kotlin Slack

Slide 130

Slide 130 text

Kotlinconf Videos list on KotlinMultiplatformStuff

Slide 131

Slide 131 text

For Libraries? Check out Stately

Slide 132

Slide 132 text

check out yours!

Slide 133

Slide 133 text

No content

Slide 134

Slide 134 text

[email protected] @kpgalligan

Slide 135

Slide 135 text

[email protected] @kpgalligan Join the team !