2019-04-28 22:43:54 +02:00
|
|
|
package org.schabi.newpipe.local.subscription
|
|
|
|
|
|
|
|
import android.app.Application
|
|
|
|
import androidx.lifecycle.AndroidViewModel
|
2020-03-05 23:47:00 +01:00
|
|
|
import androidx.lifecycle.LiveData
|
2019-04-28 22:43:54 +02:00
|
|
|
import androidx.lifecycle.MutableLiveData
|
|
|
|
import com.xwray.groupie.Group
|
2020-10-31 21:55:45 +01:00
|
|
|
import io.reactivex.rxjava3.schedulers.Schedulers
|
2019-04-28 22:43:54 +02:00
|
|
|
import org.schabi.newpipe.local.feed.FeedDatabaseManager
|
|
|
|
import org.schabi.newpipe.local.subscription.item.ChannelItem
|
|
|
|
import org.schabi.newpipe.local.subscription.item.FeedGroupCardItem
|
|
|
|
import org.schabi.newpipe.util.DEFAULT_THROTTLE_TIMEOUT
|
2020-10-31 21:55:45 +01:00
|
|
|
import java.util.concurrent.TimeUnit
|
2019-04-28 22:43:54 +02:00
|
|
|
|
|
|
|
class SubscriptionViewModel(application: Application) : AndroidViewModel(application) {
|
|
|
|
private var feedDatabaseManager: FeedDatabaseManager = FeedDatabaseManager(application)
|
|
|
|
private var subscriptionManager = SubscriptionManager(application)
|
|
|
|
|
2020-03-05 23:47:00 +01:00
|
|
|
private val mutableStateLiveData = MutableLiveData<SubscriptionState>()
|
|
|
|
private val mutableFeedGroupsLiveData = MutableLiveData<List<Group>>()
|
|
|
|
val stateLiveData: LiveData<SubscriptionState> = mutableStateLiveData
|
|
|
|
val feedGroupsLiveData: LiveData<List<Group>> = mutableFeedGroupsLiveData
|
|
|
|
|
2019-04-28 22:43:54 +02:00
|
|
|
private var feedGroupItemsDisposable = feedDatabaseManager.groups()
|
2020-10-31 21:55:45 +01:00
|
|
|
.throttleLatest(DEFAULT_THROTTLE_TIMEOUT, TimeUnit.MILLISECONDS)
|
|
|
|
.map { it.map(::FeedGroupCardItem) }
|
|
|
|
.subscribeOn(Schedulers.io())
|
|
|
|
.subscribe(
|
|
|
|
{ mutableFeedGroupsLiveData.postValue(it) },
|
|
|
|
{ mutableStateLiveData.postValue(SubscriptionState.ErrorState(it)) }
|
|
|
|
)
|
2019-04-28 22:43:54 +02:00
|
|
|
|
|
|
|
private var stateItemsDisposable = subscriptionManager.subscriptions()
|
2020-10-31 21:55:45 +01:00
|
|
|
.throttleLatest(DEFAULT_THROTTLE_TIMEOUT, TimeUnit.MILLISECONDS)
|
|
|
|
.map { it.map { entity -> ChannelItem(entity.toChannelInfoItem(), entity.uid, ChannelItem.ItemVersion.MINI) } }
|
|
|
|
.subscribeOn(Schedulers.io())
|
|
|
|
.subscribe(
|
|
|
|
{ mutableStateLiveData.postValue(SubscriptionState.LoadedState(it)) },
|
|
|
|
{ mutableStateLiveData.postValue(SubscriptionState.ErrorState(it)) }
|
|
|
|
)
|
2019-04-28 22:43:54 +02:00
|
|
|
|
|
|
|
override fun onCleared() {
|
|
|
|
super.onCleared()
|
|
|
|
stateItemsDisposable.dispose()
|
|
|
|
feedGroupItemsDisposable.dispose()
|
|
|
|
}
|
|
|
|
|
|
|
|
sealed class SubscriptionState {
|
|
|
|
data class LoadedState(val subscriptions: List<Group>) : SubscriptionState()
|
|
|
|
data class ErrorState(val error: Throwable? = null) : SubscriptionState()
|
|
|
|
}
|
|
|
|
}
|