2019-07-13 01:32:00 +02:00
|
|
|
/* This Source Code Form is subject to the terms of the Mozilla Public
|
2020-07-27 18:37:09 +02:00
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
2019-07-13 01:32:00 +02:00
|
|
|
|
|
|
|
package org.mozilla.fenix.components
|
|
|
|
|
|
|
|
import androidx.fragment.app.Fragment
|
|
|
|
import androidx.lifecycle.ViewModel
|
|
|
|
import androidx.lifecycle.ViewModelProvider
|
|
|
|
import androidx.lifecycle.get
|
2019-07-16 00:54:13 +02:00
|
|
|
import mozilla.components.lib.state.Store
|
2019-07-13 01:32:00 +02:00
|
|
|
|
|
|
|
/**
|
2019-07-16 20:29:57 +02:00
|
|
|
* Generic ViewModel to wrap a State object for state restoration.
|
|
|
|
*
|
|
|
|
* @property store [Store] instance attached to [ViewModel].
|
2019-07-13 01:32:00 +02:00
|
|
|
*/
|
2019-07-16 20:29:57 +02:00
|
|
|
class StoreProvider<T : Store<*, *>>(
|
|
|
|
val store: T
|
|
|
|
) : ViewModel() {
|
2019-07-13 01:32:00 +02:00
|
|
|
|
2019-07-16 20:29:57 +02:00
|
|
|
companion object {
|
|
|
|
fun <T : Store<*, *>> get(fragment: Fragment, createStore: () -> T): T {
|
|
|
|
val factory = StoreProviderFactory(createStore)
|
2019-08-08 00:50:51 +02:00
|
|
|
val viewModel: StoreProvider<T> = ViewModelProvider(fragment, factory).get()
|
2019-07-16 00:54:13 +02:00
|
|
|
return viewModel.store
|
2019-07-13 01:32:00 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-07-16 20:29:57 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* ViewModel factory to create [StoreProvider] instances.
|
|
|
|
*
|
|
|
|
* @param createStore Callback to create a new [Store], used when the [ViewModel] is first created.
|
|
|
|
*/
|
|
|
|
class StoreProviderFactory<T : Store<*, *>>(
|
|
|
|
private val createStore: () -> T
|
|
|
|
) : ViewModelProvider.Factory {
|
|
|
|
|
|
|
|
@Suppress("UNCHECKED_CAST")
|
|
|
|
override fun <VM : ViewModel?> create(modelClass: Class<VM>): VM {
|
|
|
|
return StoreProvider(createStore()) as VM
|
|
|
|
}
|
|
|
|
}
|