Skip to content

Instantly share code, notes, and snippets.

@alfianyusufabdullah
Created November 8, 2018 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfianyusufabdullah/d934cef0dddd67ade79d337a65a9064a to your computer and use it in GitHub Desktop.
Save alfianyusufabdullah/d934cef0dddd67ade79d337a65a9064a to your computer and use it in GitHub Desktop.
Coroutine
class FootballDataManager(private val okHttpClient: OkHttpClient) {
fun loadMatch(match: String) = GlobalScope.async {
val request = Request.Builder().url(match).build()
val response = okHttpClient.newCall(request).execute()
response.body().string()
}
}
class FootballRepository(private val footballDataManager: FootballDataManager) {
fun loadMatch(match: String, callback: RepositoryCallback<MatchResponse>) = GlobalScope.launch(Dispatchers.Main) {
val requestMatch = footballDataManager.loadMatch(match)
try {
val matchData = Gson().fromJson<MatchResponse>(requestMatch.await(), MatchResponse::class.java)
callback.onSuccess(matchData)
} catch (e: Throwable) {
callback.onError(e)
}
}
}
class MatchPresenter(private val footballRepository: FootballRepository) {
companion object {
const val NEXT_MATCH = "next"
const val LAST_MATCH = "last"
}
private var job: Job? = null
private var view: MatchView? = null
fun attachView(view: MatchView?) {
this.view = view
}
fun detachView() {
this.view = null
}
fun loadMatch(match: String, leagueId: String) {
view?.onShowLoading()
val urlMatch = when (match) {
NEXT_MATCH -> "${BuildConfig.BASE_URL}eventsnextleague.php?id=$leagueId"
LAST_MATCH -> "${BuildConfig.BASE_URL}eventspastleague.php?id=$leagueId"
else -> {
""
}
}
job = footballRepository.loadMatch(urlMatch, object : RepositoryCallback<MatchResponse> {
override fun onError(e: Throwable) {
view?.onMatchEmpty()
view?.onHideLoading()
}
override fun onSuccess(data: MatchResponse) {
data.events?.let {
if (it.size > 0) {
view?.onMatchLoaded(it)
} else {
view?.onMatchEmpty()
}
} ?: kotlin.run { view?.onMatchEmpty() }
view?.onHideLoading()
}
})
}
fun cancelJob() {
job?.let {
if (it.isActive) {
it.cancel()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment