Template: let the ViewModel factory be agnostic of the host

This commit is contained in:
ganfra 2020-04-29 17:58:54 +02:00
parent 35a6f90ed6
commit 1a307a0c4d
3 changed files with 13 additions and 4 deletions

View file

@ -20,8 +20,8 @@ data class ${fragmentArgsClass}() : Parcelable
//TODO: add this fragment into FragmentModule
class ${fragmentClass} @Inject constructor(
val viewModelFactory: ${viewModelClass}.Factory
) : VectorBaseFragment() {
private val viewModelFactory: ${viewModelClass}.Factory
) : VectorBaseFragment(), ${viewModelClass}.Factory by viewModelFactory {
<#if createFragmentArgs>
private val fragmentArgs: ${fragmentArgsClass} by args()

View file

@ -1,5 +1,6 @@
package ${escapeKotlinIdentifiers(packageName)}
import com.airbnb.mvrx.ActivityViewModelContext
import com.airbnb.mvrx.FragmentViewModelContext
import com.airbnb.mvrx.MvRxViewModelFactory
import com.airbnb.mvrx.ViewModelContext
@ -18,6 +19,7 @@ class ${viewModelClass} @AssistedInject constructor(@Assisted initialState: ${vi
<#else>
: VectorViewModel<${viewStateClass}, ${actionClass}, EmptyViewEvents>(initialState) {
</#if>
@AssistedInject.Factory
interface Factory {
fun create(initialState: ${viewStateClass}): ${viewModelClass}
@ -27,8 +29,11 @@ class ${viewModelClass} @AssistedInject constructor(@Assisted initialState: ${vi
@JvmStatic
override fun create(viewModelContext: ViewModelContext, state: ${viewStateClass}): ${viewModelClass}? {
val fragment: ${fragmentClass} = (viewModelContext as FragmentViewModelContext).fragment()
return fragment.viewModelFactory.create(state)
val factory = when (viewModelContext) {
is FragmentViewModelContext -> viewModelContext.fragment as? Factory
is ActivityViewModelContext -> viewModelContext.activity as? Factory
}
return factory?.create(state) ?: error("You should let your activity/fragment implements Factory interface")
}
}

View file

@ -30,6 +30,10 @@ import io.reactivex.Single
abstract class VectorViewModel<S : MvRxState, VA : VectorViewModelAction, VE : VectorViewEvents>(initialState: S)
: BaseMvRxViewModel<S>(initialState, false) {
interface Factory<S: MvRxState> {
fun create(state: S): BaseMvRxViewModel<S>
}
// Used to post transient events to the View
protected val _viewEvents = PublishDataSource<VE>()
val viewEvents: DataSource<VE> = _viewEvents