Last active
March 31, 2019 13:49
-
-
Save CostaFot/d8be409a169210cd118d6e29bcc07c16 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* 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