Created
November 8, 2018 03:03
-
-
Save alfianyusufabdullah/d934cef0dddd67ade79d337a65a9064a to your computer and use it in GitHub Desktop.
Coroutine
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
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() | |
} | |
} |
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
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) | |
} | |
} | |
} |
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
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