package xxx.yyy.logpanecompose
import android.app.Application
class MyApp: Application() {
public val vm = LogViewModel() // private にするべきかも
companion object {
private var instance: MyApp? = null
fun getInstance(): MyApp {
if (instance == null) {
instance = MyApp()
}
return instance!!
}
}
public fun getViewModel() = vm
}
Model に LiveData を追加して ViewModel で監視するには下のように Model を追加し、 ViewModel を変更する。
// 省略
data class LogModel(val message: String) {
val buffer = MutableLiveData(message)
fun append(newMessage: String) {
buffer.value += newMessage + "\n"
}
}
class LogViewModel(val model: LogModel): ViewModel() {
var buffer = MutableLiveData("")
private val lifecycleOwner = CustomLifecycleOwner()
init {
lifecycleOwner.start()
model.buffer.observe(lifecycleOwner) {
println("viewmodel: $it")
buffer.value = it
}
}
fun append(newMessage: String) {
model.append(newMessage)
}
inner class CustomLifecycleOwner: LifecycleOwner {
private val registry = LifecycleRegistry(this)
override val lifecycle: Lifecycle
get() = registry
fun start() {
registry.currentState = Lifecycle.State.STARTED
}
@Suppress("unused")
fun stop() {
registry.currentState = Lifecycle.State.CREATED
}
}
}
MyApp もモデルを宣言するように変更する
package xxx.yyy.logpanecompose
import android.app.Application
class MyApp: Application() {
val model = LogModel("")
val vm = LogViewModel(model=model)
companion object {
private var instance: MyApp? = null
fun getInstance(): MyApp {
if (instance == null) {
instance = MyApp()
}
return instance!!
}
}
fun getViewModel() = vm
}