icerockdev / moko-mvvm

Model-View-ViewModel architecture components for mobile (android & ios) Kotlin Multiplatform development
https://moko.icerock.dev/
Apache License 2.0
1k stars 95 forks source link

Use MutableLiveData with Model #49

Closed Diy2210 closed 4 years ago

Diy2210 commented 4 years ago

I try use MutableLiveData with Model, but it not work for me. My Model: Снимок экрана 2020-07-01 в 16 31 03

My Screen Model: Снимок экрана 2020-07-01 в 16 30 44 Снимок экрана 2020-07-01 в 16 30 53

And use in Screen: Снимок экрана 2020-07-01 в 16 31 40

And I dont understand how use MutableLiveData type - Int. I try get value like this: Снимок экрана 2020-07-01 в 16 31 50

But its not work: Снимок экрана 2020-07-01 в 16 32 02

And one more question, how use MutableLiveData type Array.

DevTchernov commented 4 years ago

text = const ... There is should be something like: text = viewModel.updates.map{"Available: $it"}

Diy2210 commented 4 years ago

text = const ... There is should be something like: text = viewModel.updates.map{"Available: $it"} Tnx! And one more question, how use MutableLiveData type Array(String)

Alex009 commented 4 years ago

LiveData and MutableLiveData is just reactive data holders. you can create LiveData with List, or Array of strings code:

private val _updates: MutableLiveData<List<String>> = MutableLiveData(emptyList())
val updates: LiveData<List<String>> = _updates

and later you can map it to any other value. for example if you want show count of items, do:

val updatesCount: LiveData<Int> = updates.map { list: List<String> -> 
    list.count 
}

or if you want join string:

val updatesString: LiveData<String> = updates.map { list: List<String> -> 
    list.joinToString()
}

to change value you just set value in MutableLiveData:

_updates.value = listOf("first", "second")

to listen changes you can use:

updates.addObserver { data ->
    println("data: $data")
}

it called in each widget

Diy2210 commented 4 years ago

Awesome, tnx!