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

Napa Ram

06/07/2021, 11:11 AM
Hi Everyone can anyone guide me how i can use ViewModel in KMM Is there any example with Use Case, Repository and ViewModel in CommonMain
b

Benoît

06/07/2021, 11:26 AM
I wouldn't recommend using Android's ViewModel in your commonMain, instead you can write your business logic in a platform agnostic way and have a ViewModel use this logic on Android, and do the same thing in a UIViewController on iOS. Although, if you really want to refer to Android's ViewModels in commonMain, then you can do the following:
Copy code
// in commonMain
expect abstract class ViewModel

// in androidMain
actual typealias ViewModel =  androidx.lifecycle.ViewModel

// in iosMain
actual abstract class ViewModel
n

Napa Ram

06/07/2021, 11:58 AM
@Benoît as per POC requirement we are trying to put ViewModel Use Case and Repository in CommonMain Only UI part will in Android and in iOS
if you have any example on github let me know
b

Benoît

06/07/2021, 12:29 PM
The architecture I'm using heavily uses functional programming and thus would probably not be what you're looking for. If you really have to make your VM class extend
androidx.lifecycle.ViewModel
then you can do what I said above with the expect/actual keywords
c

Colton Idle

06/07/2021, 4:07 PM
Reminder that if you are building a full compose app you don't have to use AAC VM but you can instead just create your own concept of a VM.
1
n

Napa Ram

06/08/2021, 10:57 AM
@joney @Colton Idle @Benoît if we create our own ViewModel then how we can achieve screen rotation and how we can achieve life cycle aware benefit, please suggest if there is any good example
b

Benoît

06/08/2021, 11:00 AM
Being lifecycle aware is an Android thing, it has to be implemented in an
android
module not a
common
one
You should decouple your business logic and use cases from Android's ViewModel, then implement these uses cases in a ViewModel and a UIViewController
The code you'll have to write in these ViewModel/UIViewController should be minimal. Even though it's a bit more code to write, it makes it a much better architecture with proper separation of concerns
n

Napa Ram

06/08/2021, 12:13 PM
@Benoît Thanks
👍 1
c

Colton Idle

06/08/2021, 12:38 PM
@Napa Ram compose handles configuration changes (e.g. rotation) with composition locals.
m

Mustafa Ozhan

06/09/2021, 8:54 PM
you can check my project i have the viewmodels shared 🙂 it is in
client
module https://github.com/CurrencyConverterCalculator/CCC
9 Views