Slide 1

Slide 1 text

@marcoGomier Marco Gomiero Senior Android Developer @ Airalo Google Developer Expert for Kotlin From Android to Multiplatform and beyond

Slide 2

Slide 2 text

@marcoGomier • Started in 2016 as an Android library RSSParser • Time to make it Multiplatform!

Slide 3

Slide 3 text

@marcoGomier Project Structure

Slide 4

Slide 4 text

@marcoGomier Android Library Source Set

Slide 5

Slide 5 text

@marcoGomier Kotlin Multiplatform Source Sets Android Library Source Set

Slide 6

Slide 6 text

@marcoGomier How to migrate to Multiplaform source sets?

Slide 7

Slide 7 text

@marcoGomier * without losing git and contributors history How to migrate to Multiplaform source sets? *

Slide 8

Slide 8 text

@marcoGomier Create a new library project

Slide 9

Slide 9 text

@marcoGomier Create a new library project https://terrakok.github.io/kmp-web-wizard/

Slide 10

Slide 10 text

@marcoGomier Create a new library project

Slide 11

Slide 11 text

@marcoGomier • Move the new source sets inside the existing library project • Rename the old source set • Duplicate and keep the old source set in the repo (for reference) • Move the existing code to the androidMain source set • Make the Android part work as before without sharing The Recipe

Slide 12

Slide 12 text

@marcoGomier • Move the new source sets inside the existing library project • Rename the old source set • Duplicate and keep the old source set in the repo (for reference) • Move the existing code to the androidMain source set • Make the Android part work as before without sharing The Recipe

Slide 13

Slide 13 text

@marcoGomier • Move the new source sets inside the existing library project • Rename the old source set • Duplicate and keep the old source set in the repo (for reference) • Move the existing code to the androidMain source set • Make the Android part work as before without sharing The Recipe

Slide 14

Slide 14 text

@marcoGomier • Move the new source sets inside the existing library project • Rename the old source set • Duplicate and keep the old source set in the repo (for reference) • Move the existing code to the androidMain source set • Make the Android part work as before without sharing The Recipe

Slide 15

Slide 15 text

@marcoGomier Platform-specific APIs

Slide 16

Slide 16 text

@marcoGomier RSSParser pre-multiplatform class Parser private constructor( private var callFactory: Call.Factory, private val charset: Charset? = null, ) { suspend fun getChannel(url: String): Channel = withContext(coroutineContext) { // If the charset is null, then "null" is saved in the database. // It's easier for retrieving data afterwards val charsetString = charset.toString() val cachedFeed = cacheManager?.getCachedFeed(url, charsetString) if (cachedFeed != null) { Log.d(TAG, "Returning object from cache") return@withContext cachedFeed } else { Log.d(TAG, "Returning data from network") val xml = CoroutineEngine.fetchXML(url, callFactory) val channel = CoroutineEngine.parseXML(xml, charset) cacheManager?.cacheFeed( url = url, channel = channel, charset = charsetString, ) return@withContext channel } } }

Slide 17

Slide 17 text

@marcoGomier suspend fun getChannel(url: String): Channel = withContext(coroutineContext) { // If the charset is null, then "null" is saved in the database. // It's easier for retrieving data afterwards val charsetString = charset.toString() val cachedFeed = cacheManager?.getCachedFeed(url, charsetString) if (cachedFeed != null) { Log.d(TAG, "Returning object from cache") return@withContext cachedFeed } else { Log.d(TAG, "Returning data from network") val xml = CoroutineEngine.fetchXML(url, callFactory) val channel = CoroutineEngine.parseXML(xml, charset) cacheManager?.cacheFeed( url = url, channel = channel, charset = charsetString, ) return@withContext channel } } }

Slide 18

Slide 18 text

@marcoGomier suspend fun getChannel(url: String): Channel = withContext(coroutineContext) { // If the charset is null, then "null" is saved in the database. // It's easier for retrieving data afterwards val charsetString = charset.toString() val cachedFeed = cacheManager?.getCachedFeed(url, charsetString) if (cachedFeed != null) { Log.d(TAG, "Returning object from cache") return@withContext cachedFeed } else { Log.d(TAG, "Returning data from network") val xml = CoroutineEngine.fetchXML(url, callFactory) val channel = CoroutineEngine.parseXML(xml, charset) cacheManager?.cacheFeed( url = url, channel = channel, charset = charsetString, ) return@withContext channel } } }

Slide 19

Slide 19 text

@marcoGomier class Parser private constructor( private var callFactory: Call.Factory, private val charset: Charset? = null, ) { suspend fun getChannel(url: String): Channel = withContext(coroutineContext) { // If the charset is null, then "null" is saved in the database. // It's easier for retrieving data afterwards val charsetString = charset.toString() val cachedFeed = cacheManager?.getCachedFeed(url, charsetString) if (cachedFeed != null) { Log.d(TAG, "Returning object from cache") return@withContext cachedFeed } else { Log.d(TAG, "Returning data from network") val xml = CoroutineEngine.fetchXML(url, callFactory) cacheManager?.cacheFeed( url = url, channel = channel, charset = charsetString, ) return@withContext channel } } } import okhttp3.Call import okhttp3.Callback import okhttp3.Request import okhttp3.Response val channel = CoroutineEngine.parseXML(xml, charset) cacheManager?.cacheFeed( url = url, channel = channel, import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserFactory

Slide 20

Slide 20 text

@marcoGomier 🤔

Slide 21

Slide 21 text

@marcoGomier Expect/Actual https://kotlinlang.org/docs/multiplatform-connect-to-apis.html

Slide 22

Slide 22 text

@marcoGomier internal interface XmlFetcher { suspend fun fetchXml(url: String): ParserInput } Interface

Slide 23

Slide 23 text

@marcoGomier internal interface XmlFetcher { suspend fun fetchXml(url: String): ParserInput } internal class JvmXmlFetcher( private val callFactory: Call.Factory, ): XmlFetcher { override suspend fun fetchXml(url: String): ParserInput { val request = createRequest(url) return ParserInput( inputStream = callFactory.newCall(request).await() ) } } internal class IosXmlFetcher( private val nsUrlSession: NSURLSession, ): XmlFetcher { override suspend fun fetchXml(url: String): ParserInput = suspendCancellableCoroutine { continuation -> ... } }

Slide 24

Slide 24 text

@marcoGomier internal interface XmlParser { suspend fun parseXML(input: ParserInput): RssChannel } Interface

Slide 25

Slide 25 text

@marcoGomier internal class AndroidXmlParser( private val dispatcher: CoroutineDispatcher, ) : XmlParser { override suspend fun parseXML(input: ParserInput): RssChannel = withContext(dispatcher) { val factory = XmlPullParserFactory.newInstance() ... } } internal interface XmlParser { suspend fun parseXML(input: ParserInput): RssChannel } internal class IosXmlParser( private val dispatcher: CoroutineDispatcher, ) : XmlParser { override suspend fun parseXML(input: ParserInput): RssChannel = withContext(dispatcher) { suspendCancellableCoroutine { continuation -> ... } } } internal class JvmXmlParser( private val dispatcher: CoroutineDispatcher, ) : XmlParser { override suspend fun parseXML(input: ParserInput): RssChannel = withContext(dispatcher) { val parser = SAXParserFactory.newInstance().newSAXParser() ... } }

Slide 26

Slide 26 text

@marcoGomier class RssParser internal constructor( private val xmlFetcher: XmlFetcher, private val xmlParser: XmlParser, ) { suspend fun getRssChannel(url: String): RssChannel = withContext(coroutineContext) { val parserInput = xmlFetcher.fetchXml(url) return@withContext xmlParser.parseXML(parserInput) } } @marcoGomier

Slide 27

Slide 27 text

@marcoGomier Prefer interfaces, if possible class RssParser internal constructor( private val xmlFetcher: XmlFetcher, private val xmlParser: XmlParser, ) { suspend fun getRssChannel(url: String): RssChannel = withContext(coroutineContext) { val parserInput = xmlFetcher.fetchXml(url) return@withContext xmlParser.parseXML(parserInput) } }

Slide 28

Slide 28 text

@marcoGomier Expect/Actual internal expect class ParserInput internal actual data class ParserInput( val inputStream: InputStream ) internal actual data class ParserInput( val data: NSData )

Slide 29

Slide 29 text

@marcoGomier Networking

Slide 30

Slide 30 text

@marcoGomier Ktor? OkHttp? Platform-specific APIs?

Slide 31

Slide 31 text

@marcoGomier • Keep using OKhttp on Android and JVM • Use NSURLSession on iOS • Backward compatibility and popularity internal class JvmXmlFetcher( private val callFactory: Call.Factory, ): XmlFetcher { override suspend fun fetchXml(url: String): ParserInput { val request = createRequest(url) return ParserInput( inputStream = callFactory.newCall(request).await() ) } } internal class IosXmlFetcher( private val nsUrlSession: NSURLSession, ): XmlFetcher { override suspend fun fetchXml(url: String): ParserInput = suspendCancellableCoroutine { continuation -> ... } }

Slide 32

Slide 32 text

@marcoGomier Constructors

Slide 33

Slide 33 text

@marcoGomier Creating an RssParser Instance • Create an instance with platform-specific dependencies (OkHttp, NSURLSession) • Create an instance with default values • Create an instance from a KMP, Android, or JVM project

Slide 34

Slide 34 text

@marcoGomier Create an instance with platform-specific dependencies class RssParser internal constructor( private val xmlFetcher: XmlFetcher, private val xmlParser: XmlParser, ) { internal interface Builder { fun build(): RssParser } }

Slide 35

Slide 35 text

@marcoGomier class RssParserBuilder( private val callFactory: Call.Factory = OkHttpClient(), private val charset: Charset? = null, ): RssParser.Builder { override fun build(): RssParser { return RssParser( xmlFetcher = JvmXmlFetcher( callFactory = callFactory, ), xmlParser = AndroidXmlParser( charset = charset, dispatcher = Dispatchers.IO, ), ) } }

Slide 36

Slide 36 text

@marcoGomier class RssParserBuilder( private val callFactory: Call.Factory = OkHttpClient(), private val charset: Charset? = null, ): RssParser.Builder { override fun build(): RssParser { return RssParser( xmlFetcher = JvmXmlFetcher( callFactory = callFactory, ), xmlParser = AndroidXmlParser( charset = charset, dispatcher = Dispatchers.IO, ), ) } }

Slide 37

Slide 37 text

@marcoGomier class RssParserBuilder( private val callFactory: Call.Factory = OkHttpClient(), private val charset: Charset? = null, ): RssParser.Builder { override fun build(): RssParser { return RssParser( xmlFetcher = JvmXmlFetcher( callFactory = callFactory, ), xmlParser = AndroidXmlParser( charset = charset, dispatcher = Dispatchers.IO, ), ) } }

Slide 38

Slide 38 text

@marcoGomier class RssParserBuilder( private val callFactory: Call.Factory = OkHttpClient(), private val charset: Charset? = null, ): RssParser.Builder { override fun build(): RssParser { return RssParser( xmlFetcher = JvmXmlFetcher( callFactory = callFactory, ), xmlParser = JvmXmlParser( charset = charset, dispatcher = Dispatchers.IO, ), ) } }

Slide 39

Slide 39 text

@marcoGomier class RssParserBuilder( private val nsUrlSession: NSURLSession = NSURLSession.sharedSession, ): RssParser.Builder { override fun build(): RssParser { return RssParser( xmlFetcher = IosXmlFetcher( nsUrlSession = nsUrlSession, ), xmlParser = IosXmlParser( Dispatchers.IO ), ) } }

Slide 40

Slide 40 text

@marcoGomier class RssParserBuilder( private val nsUrlSession: NSURLSession = NSURLSession.sharedSession, ): RssParser.Builder { override fun build(): RssParser { return RssParser( xmlFetcher = IosXmlFetcher( nsUrlSession = nsUrlSession, ), xmlParser = IosXmlParser( Dispatchers.IO ), ) } }

Slide 41

Slide 41 text

@marcoGomier class RssParserBuilder( private val nsUrlSession: NSURLSession = NSURLSession.sharedSession, ): RssParser.Builder { override fun build(): RssParser { return RssParser( xmlFetcher = IosXmlFetcher( nsUrlSession = nsUrlSession, ), xmlParser = IosXmlParser( Dispatchers.IO ), ) } }

Slide 42

Slide 42 text

@marcoGomier Create an instance with default values expect fun RssParser(): RssParser

Slide 43

Slide 43 text

@marcoGomier expect fun RssParser(): RssParser actual fun RssParser(): RssParser = RssParserBuilder().build()

Slide 44

Slide 44 text

@marcoGomier Testing

Slide 45

Slide 45 text

@marcoGomier How to write one test for multiple platforms?

Slide 46

Slide 46 text

@marcoGomier Create an instance with default values internal expect object XmlParserFactory { fun createXmlParser(): XmlParser }

Slide 47

Slide 47 text

@marcoGomier internal expect object XmlParserFactory { fun createXmlParser(): XmlParser } internal actual object XmlParserFactory { actual fun createXmlParser(): XmlParser = JvmXmlParser(dispatcher = UnconfinedTestDispatcher()) } internal actual object XmlParserFactory { actual fun createXmlParser(): XmlParser = AndroidXmlParser(dispatcher = UnconfinedTestDispatcher()) } internal actual object XmlParserFactory { actual fun createXmlParser(): XmlParser = IosXmlParser(dispatcher = UnconfinedTestDispatcher()) }

Slide 48

Slide 48 text

@marcoGomier Test the Parser class XmlParserTest { @Test fun channelTitle_isCorrect() = runTest { val parser = XmlParserFactory.createXmlParser() val input = readFileFromResources("test-feed.xml") val channel = parser.parseXML(input) assertEquals("channel-title", channel.title) } }

Slide 49

Slide 49 text

@marcoGomier Test the Parser class XmlParserTest { @Test fun channelTitle_isCorrect() = runTest { val parser = XmlParserFactory.createXmlParser() val input = readFileFromResources("test-feed.xml") val channel = parser.parseXML(input) assertEquals("channel-title", channel.title) } }

Slide 50

Slide 50 text

@marcoGomier Test the Parser

Slide 51

Slide 51 text

@marcoGomier Test the Parser • Run tests on all the platforms • Run tests on a specific platform

Slide 52

Slide 52 text

@marcoGomier Test the Parser • Run tests on all the platforms • Run tests on a specific platform

Slide 53

Slide 53 text

@marcoGomier Test the Parser • Run tests on all the platforms • Run tests on a specific platform

Slide 54

Slide 54 text

@marcoGomier Test the Parser • Run tests on all the platforms • Run tests on a specific platform

Slide 55

Slide 55 text

@marcoGomier Test the Parser • Run tests on all the platforms • Run tests on a specific platform

Slide 56

Slide 56 text

@marcoGomier Test the Parser • Run tests on all the platforms • Run tests on a specific platform

Slide 57

Slide 57 text

@marcoGomier Test the Parser • Run tests on all the platforms • Run tests on a specific platform

Slide 58

Slide 58 text

@marcoGomier Test the Parser class XmlParserTest { @Test fun channelTitle_isCorrect() = runTest { val parser = XmlParserFactory.createXmlParser() val input = readFileFromResources("test-feed.xml") val channel = parser.parseXML(input) assertEquals("channel-title", channel.title) } }

Slide 59

Slide 59 text

@marcoGomier Test the Parser class XmlParserTest { @Test fun channelTitle_isCorrect() = runTest { val parser = XmlParserFactory.createXmlParser() val input = readFileFromResources("test-feed.xml") val channel = parser.parseXML(input) assertEquals("channel-title", channel.title) } }

Slide 60

Slide 60 text

@marcoGomier Gradle sets the test process's working directory to the module's directory Read files in tests but ... • No java.io.File on Kotlin/Native • On iOS, the working directory is unrelated to the project directory

Slide 61

Slide 61 text

@marcoGomier Use Environmental Variables!💡

Slide 62

Slide 62 text

@marcoGomier val rootDir = "${rootProject.rootDir.path}/rssparser/src/commonTest/resources"

Slide 63

Slide 63 text

@marcoGomier val rootDir = "${rootProject.rootDir.path}/rssparser/src/commonTest/resources" tasks.withType().configureEach { environment("TEST_RESOURCES_ROOT", rootDir) }

Slide 64

Slide 64 text

@marcoGomier val rootDir = "${rootProject.rootDir.path}/rssparser/src/commonTest/resources" tasks.withType().configureEach { environment("TEST_RESOURCES_ROOT", rootDir) } tasks.withType().configureEach { environment("TEST_RESOURCES_ROOT", rootDir) }

Slide 65

Slide 65 text

@marcoGomier val rootDir = "${rootProject.rootDir.path}/rssparser/src/commonTest/resources" tasks.withType().configureEach { environment("TEST_RESOURCES_ROOT", rootDir) } tasks.withType().configureEach { environment("TEST_RESOURCES_ROOT", rootDir) environment("SIMCTL_CHILD_TEST_RESOURCES_ROOT", rootDir) } https://stackover fl ow.com/a/53604237/5264056

Slide 66

Slide 66 text

@marcoGomier Read files in tests internal expect fun readFileFromResources( resourceName: String ): ParserInput

Slide 67

Slide 67 text

@marcoGomier internal actual fun readFileFromResources( resourceName: String, ): ParserInput { val path = System.getenv("TEST_RESOURCES_ROOT") val file = File("$path/$resourceName") return ParserInput( inputStream = FileInputStream(file) ) } internal expect fun readFileFromResources( resourceName: String ): ParserInput

Slide 68

Slide 68 text

@marcoGomier internal expect fun readBinaryResource( resourceName: String, ): ParserInput internal actual fun readFileFromResources( resourceName: String ): ParserInput { val s = getenv("TEST_RESOURCES_ROOT")?.toKString() val path = "$s/${resourceName}" val data = NSData.dataWithContentsOfFile(path) return ParserInput(requireNotNull(data)) } internal actual fun readFileFromResources( resourceName: String, ): ParserInput { val path = System.getenv("TEST_RESOURCES_ROOT") val file = File("$path/$resourceName") return ParserInput( inputStream = FileInputStream(file) ) }

Slide 69

Slide 69 text

@marcoGomier Publishing

Slide 70

Slide 70 text

@marcoGomier • Nothing to do! \o/ Publishing https://github.com/vanniktech/gradle-maven-publish-plugin

Slide 71

Slide 71 text

@marcoGomier Desktop (JVM), Android, iOS

Slide 72

Slide 72 text

@marcoGomier Desktop (JVM), Android, iOS, macOS, tvOS, watchOS*

Slide 73

Slide 73 text

@marcoGomier Maybe in the future •JS •WebAssembly •Windows •Linux

Slide 74

Slide 74 text

@marcoGomier Conclusions

Slide 75

Slide 75 text

@marcoGomier Conclusions • Adapting to different platforms requires time and thinking • Code organisation can be challenging, especially for maintaining git history • Prefer Interfaces over expect/actual, where possible

Slide 76

Slide 76 text

@marcoGomier https://github.com/prof18/RSS-Parser

Slide 77

Slide 77 text

@marcoGomier https://thebakery.dev/52/

Slide 78

Slide 78 text

@marcoGomier feed fl ow.dev/

Slide 79

Slide 79 text

@marcoGomier Thank you! > Twitter: @marcoGomier > Github: prof18 > Website: marcogomiero.com > Mastodon: androiddev.social/@marcogom Marco Gomiero Senior Android Developer @ Airalo Google Developer Expert for Kotlin

Slide 80

Slide 80 text

Bibliography / Useful Links • https: // kotlinlang.org/docs/multiplatform-mobile-understand-project- structure.html#source-sets • https: // kotlinlang.org/docs/multiplatform-connect-to-apis.html • https: // square.github.io/okhttp/ • https: // ktor.io/ • https: // developer.apple.com/documentation/foundation/nsurlsession • https: // kotlinlang.org/docs/multiplatform-run-tests.html • https: // publicobject.com/2023/04/16/read-a-project-file-in-a-kotlin-multiplatform-test/ • https: // github.com/vanniktech/gradle-maven-publish-plugin • https: // github.com/prof18/RSS-Parser • https: // thebakery.dev/52/ • https: // www.feedflow.dev/