-
-
Notifications
You must be signed in to change notification settings - Fork 445
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: use a view model for the trends fragment
- Loading branch information
1 parent
4cd6552
commit eda53be
Showing
2 changed files
with
62 additions
and
46 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
app/src/main/java/com/github/libretube/ui/models/TrendsViewModel.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package com.github.libretube.ui.models | ||
|
||
import android.content.Context | ||
import android.util.Log | ||
import android.widget.Toast | ||
import androidx.lifecycle.MutableLiveData | ||
import androidx.lifecycle.ViewModel | ||
import androidx.lifecycle.viewModelScope | ||
import com.github.libretube.R | ||
import com.github.libretube.api.RetrofitInstance | ||
import com.github.libretube.api.obj.StreamItem | ||
import com.github.libretube.extensions.TAG | ||
import com.github.libretube.helpers.LocaleHelper | ||
import com.github.libretube.util.deArrow | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.launch | ||
import kotlinx.coroutines.withContext | ||
import retrofit2.HttpException | ||
import java.io.IOException | ||
|
||
class TrendsViewModel: ViewModel() { | ||
val trendingVideos = MutableLiveData<List<StreamItem>>() | ||
|
||
fun fetchTrending(context: Context) { | ||
viewModelScope.launch { | ||
try { | ||
val region = LocaleHelper.getTrendingRegion(context) | ||
val response = withContext(Dispatchers.IO) { | ||
RetrofitInstance.api.getTrending(region).deArrow() | ||
} | ||
trendingVideos.postValue(response) | ||
} catch (e: IOException) { | ||
println(e) | ||
Log.e(TAG(), "IOException, you might not have internet connection") | ||
Toast.makeText(context, R.string.unknown_error, Toast.LENGTH_SHORT).show() | ||
return@launch | ||
} catch (e: HttpException) { | ||
Log.e(TAG(), "HttpException, unexpected response") | ||
Toast.makeText(context, R.string.server_error, Toast.LENGTH_SHORT).show() | ||
return@launch | ||
} | ||
} | ||
} | ||
} |