Skip to content

Commit 404c13d

Browse files
StypoxIsira-Seneviratne
authored andcommitted
Improve FeedViewModel factory
1 parent 5c68c8e commit 404c13d

2 files changed

Lines changed: 14 additions & 18 deletions

File tree

app/src/main/java/org/schabi/newpipe/local/feed/FeedFragment.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,8 @@ class FeedFragment : BaseStateFragment<FeedState>() {
135135
_feedBinding = FragmentFeedBinding.bind(rootView)
136136
super.onViewCreated(rootView, savedInstanceState)
137137

138-
val factory = FeedViewModel.Factory(requireContext(), groupId)
139-
viewModel = ViewModelProvider(this, factory).get(FeedViewModel::class.java)
138+
val factory = FeedViewModel.getFactory(requireContext(), groupId)
139+
viewModel = ViewModelProvider(this, factory)[FeedViewModel::class.java]
140140
showPlayedItems = viewModel.getShowPlayedItemsFromPreferences()
141141
showFutureItems = viewModel.getShowFutureItemsFromPreferences()
142142
viewModel.stateLiveData.observe(viewLifecycleOwner) { it?.let(::handleResult) }

app/src/main/java/org/schabi/newpipe/local/feed/FeedViewModel.kt

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ import androidx.core.content.edit
55
import androidx.lifecycle.LiveData
66
import androidx.lifecycle.MutableLiveData
77
import androidx.lifecycle.ViewModel
8-
import androidx.lifecycle.ViewModelProvider
8+
import androidx.lifecycle.viewmodel.initializer
9+
import androidx.lifecycle.viewmodel.viewModelFactory
910
import androidx.preference.PreferenceManager
1011
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
1112
import io.reactivex.rxjava3.core.Flowable
@@ -139,21 +140,16 @@ class FeedViewModel(
139140
private fun getShowFutureItemsFromPreferences(context: Context) =
140141
PreferenceManager.getDefaultSharedPreferences(context)
141142
.getBoolean(context.getString(R.string.feed_show_future_items_key), true)
142-
}
143-
144-
class Factory(
145-
private val context: Context,
146-
private val groupId: Long = FeedGroupEntity.GROUP_ALL_ID
147-
) : ViewModelProvider.Factory {
148-
@Suppress("UNCHECKED_CAST")
149-
override fun <T : ViewModel> create(modelClass: Class<T>): T {
150-
return FeedViewModel(
151-
context.applicationContext,
152-
groupId,
153-
// Read initial value from preferences
154-
getShowPlayedItemsFromPreferences(context.applicationContext),
155-
getShowFutureItemsFromPreferences(context.applicationContext)
156-
) as T
143+
fun getFactory(context: Context, groupId: Long) = viewModelFactory {
144+
initializer {
145+
FeedViewModel(
146+
context.applicationContext,
147+
groupId,
148+
// Read initial value from preferences
149+
getShowPlayedItemsFromPreferences(context.applicationContext),
150+
getShowFutureItemsFromPreferences(context.applicationContext)
151+
)
152+
}
157153
}
158154
}
159155
}

0 commit comments

Comments
 (0)