-
Notifications
You must be signed in to change notification settings - Fork 0
Interractors
kaloglu edited this page Jun 14, 2020
·
2 revisions
Sample for Implementation UseCase
@ExperimentalCoroutinesApi
@InternalCoroutinesApi
class GetTweetList(
private val repository: TweetListRepository = TweetListRepository.getInstance()
)
: UseCase<List<TweetWithUser>, TimelineResult<SdkTweet>, GetTweetList.Request>() {
override var request: Request = Request()
override fun registerLifecycle(lifecycle: Lifecycle) {
super.registerLifecycle(lifecycle)
repository.registerLifecycle(lifecycle)
}
override suspend fun saveCallResult(result: TimelineResult<SdkTweet>) =
repository.insertAll(result.items.mapToRoomModel())
override fun createCall() = fetchData<TimelineResult<SdkTweet>>(request.userId, request.count)
override fun shouldFetch(data: List<TweetWithUser>) = data.isEmpty() || data.first().tweet.cachedAt.isToday().not()
override fun loadFromDb() = repository.get(request.userId, request.count) // Flowable
fun execute(userId: Long) {
request.userId = userId
return execute()
}
fun onEach(action: suspend (Resource<List<TweetWithUser>>) -> Unit) =
this.flow.onEach(action).launchIn(coroutineScope)
@Throws(TwitterException::class)
fun <R : TimelineResult<SdkTweet>> fetchData(userId: Long?, count: Int = 20): Flow<R> {
val fetch: MutableLiveData<R> = MutableLiveData()
//region Twitter SDK implementation
val userTimeline = UserTimeline.Builder()
.userId(userId)
.includeReplies(false)
.includeRetweets(false)
.maxItemsPerRequest(count)
.build()
userTimeline.next(null, object : Callback<TimelineResult<SdkTweet>>() {
@Suppress("UNCHECKED_CAST")
override fun success(result: Result<TimelineResult<SdkTweet>>) {
fetch.postValue(result.data as R)
}
override fun failure(exception: TwitterException) {
Log.e("userTimeline services", exception.localizedMessage ?: "HATA")
exception.printStackTrace()
throw exception
}
})
//endregion
return fetch.asFlow()
}
data class Request(var count: Int = 10) : UseCase.Request {
var userId by Delegates.notNull<Long>()
}
}
Full sample for databinding4vm : https://github.com/kaloglu/androtweet