Skip to content

Instantly share code, notes, and snippets.

@CostaFot
Last active March 31, 2019 13:49
Show Gist options
  • Save CostaFot/d8be409a169210cd118d6e29bcc07c16 to your computer and use it in GitHub Desktop.
Save CostaFot/d8be409a169210cd118d6e29bcc07c16 to your computer and use it in GitHub Desktop.
/**
* Instantiating this guy with the NowPlayingMoviesViewModelFactory
* The factory comes in ready with everything bundled from the AppModule so have at it
*/
class NowPlayingMoviesViewModel(
private val placeholderApi: MovieApi,
private val apiKey: String,
private val scheduler: Scheduler
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private var latestMoviesCall: Disposable? = null
val moviesData = MutableLiveData<Movies>()
/**
* Execute the API call to get some movies
* Not explaining this one as Retrofit isn't the point for this example
*/
fun getNowPlayingMovies() {
latestMoviesCall?.dispose()
latestMoviesCall = placeholderApi.getNowPlayingMovies(apiKey)
.subscribeOn(scheduler)
.doOnSubscribe { compositeDisposable.add(it) }
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
moviesData.postValue(it)
Timber.d("wew lad things went well")
},
{
moviesData.postValue(null)
Timber.d("Oopsie doopsie")
}
)
}
private fun cancelAllJobs() {
compositeDisposable.clear()
}
// Killing all background threads (if any exist) cause they don't deserve to live when the activity is not running
override fun onCleared() {
cancelAllJobs()
super.onCleared()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment