NetworkDataSource

Network data source for fetching remote data via REST API.

This interface defines the contract for making network requests to retrieve data from remote endpoints. It serves as an abstraction layer over the underlying REST API implementation, allowing repositories to fetch network data without depending on specific HTTP client details.

Design Pattern

This follows the Data Source Pattern:

  • Encapsulates all network communication logic

  • Returns domain-agnostic network models (NetworkPost)

  • Throws exceptions on network errors (handled by repositories with suspendRunCatching)

  • Executes on IO dispatcher (automatically handled by implementation)

Usage in Repositories

class PostsRepository @Inject constructor(
private val networkDataSource: NetworkDataSource,
private val localDataSource: LocalDataSource
) {
suspend fun syncPosts(): Result<Unit> = suspendRunCatching {
val networkPosts = networkDataSource.getPosts()
localDataSource.savePosts(networkPosts.map { it.toEntity() })
}

suspend fun getPostById(id: Int): Result<Post> = suspendRunCatching {
networkDataSource.getPost(id).toDomainModel()
}
}

Error Handling

This interface does not return Result types. Instead:

  • Network errors throw IOException

  • HTTP errors throw HttpException

  • Repositories should wrap calls with suspendRunCatching

Threading

All suspend functions execute on the IO dispatcher automatically. Callers should not wrap calls with withContext - the implementation handles dispatching.

See also

Functions

Link copied to clipboard
abstract suspend fun getPost(id: Int): NetworkPost

Fetches a single post by ID from the remote API.

Link copied to clipboard
abstract suspend fun getPosts(): List<NetworkPost>

Fetches all posts from the remote API.